Stubbing directly vs using stub method

I use RSpec mock and stub like this:

hit = mock(“hit”, :stored => 5)

This works fine, but when using this instead:

hit = mock(“hit”).stub(:stored) { 5 }

then I get

undefined method `stored’ for #<RSpec::Mocks::MessageExpectation:
0xb688bb78>

I always thought both were equivalent. Can someone enlighten me?

Regards,
Kai

On Apr 2, 2011, at 8:20 AM, Kai S. wrote:

undefined method `stored’ for #<RSpec::Mocks::MessageExpectation:
0xb688bb78>

I always thought both were equivalent. Can someone enlighten me?

This error message tells you the problem: the stub method in the
second example returns an instance of RSpec::Mocks::MessageExpectation,
not the double itself. If you did it this way, you’d get what you were
looking for:

hit = mock(‘hit’)
hit.stub(:stored) { 5 }
hit.stored.should eq(5)

Make sense?

David

hit = mock(‘hit’)
hit.stub(:stored) { 5 }
hit.stored.should eq(5)

Make sense?

Of course :slight_smile: Thanks.

On Apr 2, 2011, at 6:20 AM, Kai S. wrote:

I use RSpec mock and stub like this:

hit = mock(“hit”, :stored => 5)

This works fine, but when using this instead:

hit = mock(“hit”).stub(:stored) { 5 }

Not that it’s really necessary, but to make this work you can do:

hit = mock(‘hit’).tap {|h| h.stub(:stored) { 5 } }

although I prefer passing a hash into mock, much cleaner :slight_smile:

Pat

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs