Search code examples
rubytestingrspecstubbingexpectations

Does should_receive do something I don't expect?


Consider the following two trivial models:

class Iq

  def score
    #Some Irrelevant Code
  end

end

class Person

  def iq_score
    Iq.new(self).score   #error here
  end

end

And the following Rspec test:

describe "#iq_score" do

  let(:person) { Person.new }

  it "creates an instance of Iq with the person" do
    Iq.should_receive(:new).with(person)
    Iq.any_instance.stub(:score).and_return(100.0)
    person.iq_score
  end

end

When I run this test (or, rather, an analogous one), it appears the stub has not worked:

Failure/Error: person.iq_score
  NoMethodError:
    undefined method `iq_score' for nil:NilClass

The failure, as you might guess, is on the line marked "error here" above. When the should_receive line is commented out, this error disappears. What's going on?


Solution

  • You're stubbing away the initializer:

    Iq.should_receive(:new).with(person)
    

    returns nil, so Iq.new is nil. To fix, just do this:

    Iq.should_receive(:new).with(person).and_return(mock('iq', :iq_score => 34))
    person.iq_score.should == 34 // assert it is really the mock you get