Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "expect" before block to change something in rspec?

Tags:

ruby

rspec

I have a test suite structured this way:

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

Usually I would just place this block outside of context calling expect like that:

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

But it makes code a bit harder to read, since related code are placed outside of its context.

like image 939
Andrew Avatar asked May 22 '13 20:05

Andrew


2 Answers

Would you consider changing both your tests to expect syntax to get them under the same context? Perhaps something like:

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
like image 108
Paul Fioravanti Avatar answered Jan 04 '23 05:01

Paul Fioravanti


You don't set expectations on before block. Its purpose is to set up the environment (and also it's executed before the spec, so it's too late to expect something of it). You want regular let.

context "empty bowl" do
  let(:cat) { meow }

  # here I want to expect that number of PetFishes is going down after `meow`, like that
  it "will eat some pet fishes" do
    expect {cat}.to change(PetFish, :count).by(-1)
  end
end
like image 37
Sergio Tulentsev Avatar answered Jan 04 '23 07:01

Sergio Tulentsev