ruby - 我如何在 block 之前的 "expect"更改 rspec 中的某些内容?

标签 ruby rspec

我有一个这样构造的测试套件:

let(:cat) { create :blue_russian_cat } 
subject { cat }

context "empty bowl" do
  let!(:bowl) { create(:big_bowl, amount: 0) }
  before { meow }

  # a ton of `its` or `it` which require `meow` to be executed before making assertion
  its(:status) { should == :annoyed }
  its(:tail) { should == :straight }
  # ...

  # here I want to expect that number of PetFishes is going down after `meow`, like that
  it "will eat some pet fishes" do
    expect {???}.to change(PetFish, :count).by(-1)
  end
end

通常我会把这个 block 放在调用 expect 的上下文之外:

  it "will eat some pet fishes" do
    expect { meow }.to change(PetFish, :count).by(-1)
  end

但它使代码更难阅读,因为相关代码位于其上下文之外。

最佳答案

您是否会考虑将您的两个测试更改为 expect 语法以使它们处于相同的 context 下?也许是这样的:

let(:cat) { create :blue_russian_cat } 

context "empty bowl" do
  let!(:bowl) { create(:big_bowl, amount: 0) }
  let(:meowing) { -> { meow } } # not sure what meow is, so may not need lambda

  it "will annoy the cat" do
    expect(meowing).to change(cat.status).from(:placid).to(:annoyed)
  end

  # here I want to expect that number of PetFishes is going down after `meow`
  it "will eat some pet fishes" do
    expect(meowing).to change(PetFish, :count).by(-1)
  end
end

关于ruby - 我如何在 block 之前的 "expect"更改 rspec 中的某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700976/

相关文章:

ruby-on-rails - ruby on rails 中的 Controller 和 Action 有什么区别?

ruby-on-rails - 为 Rails 上的列 ruby​​ 指定默认值

ruby-on-rails - Mac 上的 Rails ActionMailer 问题

ruby - 如何在 Rails 之外将 mock_models 与 RSpec 一起使用?

ruby - 如何从 `gem` 中获取不在 `lib` 目录下的文件?

ruby - 需要在 Ruby 中进行前向声明

ruby - `nil` .to_i #=> 0`, ` "".to_i #=> 0` `nil` .to_f#=> 0. 0`, ` "".to_f#=> 0.0` 的用例

rspec - 如何在 FactoryBot 中使用 has_many 关联设置工厂

ruby - rspec 索引示例有效但不显示示例

ruby-on-rails - 每个循环使用 Rspec 的单元测试用例