应该匹配器RSpec expect语法

27

抱歉,我的意思是“应该”。 - trev9065
关于基于主要是基于个人观点而进行的关闭投票,我认为这个特定的问题询问是否某事物是一个“好主意”是一个例外,因为有一个基于事实的解释表明该问题并不重要。 - Peter Alfvin
修改了问题的细节,使其适合于SO。 - Michael Durrant
2个回答

59

尽管可以使用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 Durrant
@MichaelDurrant 是的,没错。谢谢你指出来。答案已更新。 - Peter Alfvin
有人知道这个downvote是什么意思吗?它是否与此问题被认为“主要基于观点”有关的关闭投票有关? - Peter Alfvin
很遗憾你需要 it 块。我一直喜欢 shoulda 测试框架,因为它们的语法简洁。 - trev9065
实际上,你不需要这个块。这就是我回答的要点。单行的 should 形式是完全可接受的,并且已被最新的约定完全接受/支持。但是你给了我一个想法。如果 RSpec 引入 expect_it 作为 expect(subject) 的别名会怎样呢? - Peter Alfvin

0

我将补充 @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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接