Question

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?

Was it helpful?

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

OTHER TIPS

Since RSpec has extended stubber functionality, now following way is correct:

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

It will (1) check expectation (2) return control to original function, not just return nil.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top