使用shoulda-matchers和RSpec的新expect syntax的正确格式是什么
发布于 2013-09-08 21:48:14
当然,我们可以将shoulda匹配器与新的expect语法一起使用,如下所示:
it 'should validate presence of :email' do
expect(subject).to validate_presence_of :email
end或者更简洁但可读性较差的:
it { expect(subject).to validate_presence_of :email }即使在config.syntax == :expect时,2.14中也明确支持这些匹配器通常使用的单行should格式。当 should 与隐式主语一起使用时,如:
describe User
it { should validate_presence_of :email }
end它不依赖于 should 在其他方面所依赖的的猴子修补。
这在https://github.com/rspec/rspec-expectations/blob/master/Should.md中有介绍。实际上,该文档甚至使用上面shoulda匹配器示例来说明此异常。
另请参阅Using implicit subject with expect in RSpec-2.11,其中讨论了一个配置选项,该选项允许您使用作为it的替代方案。
expect_it { to validate_presence_of :email }更新:从RSpec 3.0 (beta2)开始,您还可以使用:
it { is_expected.to validate_presence_of :email }发布于 2015-10-06 01:47:22
我将补充@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) }
endhttps://stackoverflow.com/questions/18680131
复制相似问题