使用 shoulda-matchers 和 RSpec 的新的 expect 语法 的正确格式是什么?
尽管可以使用shoulda-matchers与新的expect语法,如下所示:
it 'should validate presence of :email' do
expect(subject).to validate_presence_of :email
end
或更简洁但可读性较差的版本:
it { expect(subject).to validate_presence_of :email }
在2.14中,即使 config.syntax == :expect
,也明确支持这些匹配器所使用的一行格式。强调一下,当像这样使用隐式主语的should
时:
describe User
it { should validate_presence_of :email }
end
它不依赖于Kernel
的猴子补丁,否则应该会依赖于它。
这在https://github.com/rspec/rspec-expectations/blob/master/Should.md中有所涉及。事实上,该文档甚至使用上述shoulda
匹配器示例来说明这个异常。
另请参见在 RSpec-2.11 中使用隐式主题与 expect ,该主题讨论了一个配置选项,它可以作为一种替代方法来使用,而不是it
。
expect_it { to validate_presence_of :email }
更新:从 RSpec 3.0(beta2)开始,您还可以使用以下方式:
it { is_expected.to validate_presence_of :email }
describe User
包围,对吧?因为它看起来像是将3行与3个不同的行进行比较,但并不完全是这样。如果是这样的话,为了清晰起见,可能需要在第一个代码块中添加它。 - Michael Durrantshould
形式是完全可接受的,并且已被最新的约定完全接受/支持。但是你给了我一个想法。如果 RSpec 引入 expect_it
作为 expect(subject)
的别名会怎样呢? - Peter Alfvin我将补充 @peter-alfvin 的答案。如果您使用 shoulda-matchers
测试模型及其迁移本身,则无法在 it
块之外使用 :expect
,因此不能编写以下内容:
RSpec.describe ModelName, type: :model do
expect(subject).to belong_to(:user)
end
你会得到异常:
`expect` is not available on an example group (e.g. a `describe` or `context` block).
但正确的版本是:
RSpec.describe ModelName, type: :model do
it { expect(subject).to belong_to(:user) }
end