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
David Chelimsky
2011-Apr-02 15:04 UTC
[rspec-users] stubbing directly vs using stub method
On Apr 2, 2011, at 8:20 AM, Kai Schlamp 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 } > > then I get > > 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> Regards, > Kai
> hit = mock(''hit'') > hit.stub(:stored) { 5 } > hit.stored.should eq(5) > > Make sense?Of course :-) Thanks.
On Apr 2, 2011, at 6:20 AM, Kai Schlamp 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 :) Pat