RSpec:有没有'和'改变',例如'和_not改变'?

Jos*_*eim 26 rspec

我发现这种.and方法对于链接许多期望非常有用.

expect {
  click_button 'Update Boilerplate'
  @boilerplate_original.reload
} .to  change { @boilerplate_original.title }.to('A new boilerplate')
  .and change { @boilerplate_original.intro }.to('Some nice introduction')
Run Code Online (Sandbox Code Playgroud)

有什么让我检查没有变化

.and_not change { @boilerplate_original.intro }
Run Code Online (Sandbox Code Playgroud)

那样的东西?我找不到任何东西,而且很难在Google上搜索"而不是".

Pet*_*vin 28

不,没有and_not也没有一般否定运算符,如https://github.com/rspec/rspec-expectations/issues/493中所述

但是,有一种机制可以定义现有匹配器的否定版本,如http://www.rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers.define_negated_matcher中所述,您可以使用它and.

有关全套复合匹配器的文档,参见https://www.relishapp.com/rspec/rspec-expectations/v/3-4/docs/compound-expectations

  • tldr; 在`spec_helper.rb`中放入`RSpec :: Matchers.define_negated_matcher:not_change,:change` (16认同)

Ale*_*pov 17

如果你试图断言某些操作不应该改变计数,你可以这样做

expect { something }.to change { Foo.count }.by(1).and change { Bar.count }.by(0)
Run Code Online (Sandbox Code Playgroud)

  • 与 rspec-rubocop 相关的问题,有一个(IMO 合法的)警察鼓励您使用负匹配器而不是“按 0 更改” (2认同)

小智 13

您可以通过以下方式定义否定匹配器RSpec::Matchers.define_negated_matcher

例子

RSpec::Matchers.define_negated_matcher :not_include, :include
RSpec::Matchers.define_negated_matcher :not_eq, :eq
Run Code Online (Sandbox Code Playgroud)

将此行放在任何上下文之外的文件开头,放入另一个文件并将该文件加载到您的测试中

所以现在你可以写

expect([1, 2, 3]).to include(1).and not_include(5).and not_include(6)
expect(100).to eq(100).and not_eq(200)
Run Code Online (Sandbox Code Playgroud)