[rspec-users] setting partial stub for just one value and letting obj handle the rest
matt at mattwynne.net
Thu Apr 1 16:45:36 EDT 2010
On 1 Apr 2010, at 21:35, David Chelimsky wrote:
> On Apr 1, 2010, at 3:14 PM, drewB wrote:
>> Occasionally, I find myself in a situation where I want to have a
>> obj returned if a method is called with a particular argument but
>> handled normally otherwise. For example, lets say I have a Model
>> named User and I am specing a controller that sends messages from one
>> user to another. When User.find is called for the user who is making
>> the request I want it to run normally but when User.find is called
>> the receiver I want it to return a mocked obj. In this case, I can
>> something like (http://gist.github.com/352305):
>> user = mock_model(User)
>> User.stub!(:find).at_least(1).and_return do |id|
>> if id == mock_user.id.to_s
>> If I didn't have another method that allowed me to find a User by
>> id this won't work.
>> Is there an easier way to accomplish this?
> Not really. When you stub a method, the framework overrides that
> method with its own implementation. There's no mechanism in place to
> say "pass the message onto the real object if it doesn't have the
> arguments I'm interested in." I'm not sure of any framework that
> does that. Maybe RR, but I'm not sure.
> Good luck.
I can't help but chime in here that I would be pretty irritated to
come across a test that mixed up using mocks and real objects,
especially when they're the same class. Can you not use a mock for the
other instance of User too?
> rspec-users mailing list
> rspec-users at rubyforge.org
More information about the rspec-users