rspec before(:all) is tempting but stubs don’t play nicely with it.


I was looking at an rspec test with multiple expectations in the same example.

  before(:all) do
     SpecialClient.any_instance.stub(:login).and_return { true }
  end
#
# MUCH SPACE
#
# WOW
#

  it "does stuff successfully" do
    # preceding code, including controller action
    expect(result.valid?).to be_true
    expect(response.body).to match /All is happy/
    expect(response.code).to eq "200"
  end

I wanted to add an additional test, but didn’t want it to be lumped in the “does stuff successfully” example, so I went ahead and refactored the expectations into different examples, and ran into:

NoMethodError:
       undefined method `any_instance_recorder_for" for nil:NilClass

I found this answer on StackOverflow that helped me track down that the use of a before(:all) vs. before(:each) might be the problem.


%d bloggers like this: