您好,我是RSpec的新手,我想弄清楚将块传递给Expect{}和只使用Expect()有什么不同.

下面是一个简单的例子

require "rails_helper"
RSpec.describe "Test",type: :model do
 it "testing count" do
   arr=[1,2,3]
   expect{arr<<1}.to change{arr.count}.by(1)
 end
end

这运行得很好,但当我执行此操作时

    require "rails_helper"
    RSpec.describe "Test",type: :model do
      it "testing count" do
        arr=[1,2,3]
        expect(arr<<1).to change{arr.count}.by(1)
      end
    end

它抛出一个错误

故障:

  1) Test testing count
     Failure/Error: expect(arr<<1).to change{arr.count}.by(1)
       expected `arr.count` to have changed by 1, but was not given a block
     # ./spec/models/test_spec.rb:6:in block (2 levels) in <top (required)>

即使我不使用带有零钱的块,它也会给我一个错误

require "rails_helper"
RSpec.describe "Test",type: :model do
  it "testing count" do
    arr=[1,2,3]
    expect{arr<<1}.to change(arr.count).by(1)
  end
end

故障:

  1) Test testing count
     Failure/Error: expect{arr<<1}.to change(arr.count).by(1)
     
     ArgumentError:
       `change` requires either an object and message (`change(obj, :msg)`) or a block (`change { }`). You passed an object but no message.

有没有人能解释一下为什么会这样?

推荐答案

expect(...)语法用于预期括号中语句的return value与某个条件匹配,例如:

expect(result).to eq(3)
expect(list).not_to be_empty
expect(string).to match(/regexp/)
expect(1..10).to cover(3)

expect { ... }运行块,实际上并不关心块的返回值,而是关心在块中运行代码的side-effects.与此类似,另一个值通过运行块进行更改,或者引发异常.

expect { api_request }.to raise_error(NotFoundError)
expect { object.action }.to change(object, :value).from(old).to(new)
expect { actual }.to output("some output").to_stdout

找到更多examples in the RSpec docs

在您的示例中

expect { array << 1 }.to change { array.count }.by(1)

因为将一个值推入数组的百分之一是数组中元素的计数发生了变化.但

expect(array << 1).to change { arr.count }.by(1)

不起作用,因为expect(array << 1)return value[1, 2, 3, 1],而此语法不支持change匹配器.

Ruby-on-rails相关问答推荐

如何测试自定义路由?

RSpec系统测试无法从工厂访问新创建的记录

我如何在不在 gemfile 中的 rake 任务中要求 gem?

微软安全链接在页面加载前解锁用户

您如何测试方法调用块内调用的方法,以及使用 rspec 在块内传递给该方法调用的内容

Rails 7:加载所有刺激控制器

使用带有 bootstrap-sass gem 的 Rails 4 无法让 CSS 在 Heroku 上工作

禁用冻结字符串文字注释判断

Rails cron 与时俱进,设置环境

jbuilder vs rails-api/active_model_serializers 用于 Rails 4 中的 JSON 处理

回形针图片网址

Gem 更新:在从 ASCII-8BIT 到 UTF-8 到 US-ASCII 的转换中,无法将 "\xE7" 转换为 UTF-8

Rails ActiveRecord:验证单个属性

在 Epoch 中将 Ruby 时间戳转换为秒数并返回

Rails 3:验证组合值

带有 master.key 的 Rails 5.2 - Heroku 部署

使用god 监控独角兽 - 以非零代码开始退出 = 1

Groovy/Grails :: Ruby/Rails :: 2011 框架状态

Rails:如何修复‘生产’环境缺少 secret_key_base

Rspec:如何在控制器规范中分配实例变量