gpt4 book ai didi

ruby-on-rails - Rspec expect( ) 与 expect { }

转载 作者:行者123 更新时间:2023-12-05 09:26:41 29 4
gpt4 key购买 nike

你好我是 rspec 的新手,我想弄清楚将 block 传递给 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

它抛出一个错误

Failures:

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)>

即使我不使用带有更改的 block ,它也会给我一个错误

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(...)语法用于期望括号中语句的返回值符合特定条件,例如:

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

expect { ... }运行 block 并且并不真正关心 block 的返回值,而是关心在 block 中运行代码的副作用。就像通过运行 block 或引发异常来更改另一个值。

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)返回值[1, 2, 3, 1]并且此语法不支持 change匹配器。

关于ruby-on-rails - Rspec expect( ) 与 expect { },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73590798/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com