[rspec-users] Trouble using should_receive

Glenn Ford glenn at aldenta.com
Thu Nov 15 14:24:30 EST 2007


On Nov 15, 2007, at 2:03 PM, Pat Maddox wrote:

> On Nov 15, 2007 10:50 AM, Glenn Ford <glenn at aldenta.com> wrote:
>>
>> I have this code trying to ensure my reset method works. I want to  
>> make sure
>> all the participants have their destroy method called.
>>
>> # in my spec for Room r = Room.new(:name => 'bob') r.save p =
>> Participant.new(:login => 'a', :password =>  
>> 'b', :password_confirmation =>
>> 'b') p.room = r p.save! p.should_receive(:destroy) r.reset #in  
>> room.rb def
>> reset participants.each { |p| p.destroy } save! end
>>
>> Unfortunately it fails. I print out "p" in both locations and while  
>> they
>> have all the same data, they have different memory addresses. I  
>> don't know
>> if this is the explanation for the issue but it's all I can find so  
>> far.
>>
>> How do I fix this? Thanks!
>>
>> Glenn
>> _______________________________________________
>> rspec-users mailing list
>> rspec-users at rubyforge.org
>> http://rubyforge.org/mailman/listinfo/rspec-users
>>
>
> Hey Glenn,
>
> The problem, as you mentioned, is that the objects loaded by
> #participants don't include the object you created.  Rails does a
> "SELECT * FROM participates WHERE room_id=?" and instantiates new
> objects.
>
> The first option is to use participants#<< instead of setting the
> room.  So instead of
> p.room = r
>
> you would have
> r.partipants << p
>
> And then it ought to work.
>
> Alternatively, since you're actually hitting the database, you can  
> just do
>
> lambda { r.reset }.should change(Participant, :count).by(-1)
>
> And as a side note, AR gives you #destroy_all, so instead of iterating
> through the participants you can just do
> participants.destroy_all
>
> hth
>
> Pat

r.participants << p didn't do it, but the "should change" did and I  
like that solution best.  Court3nay also suggested "r.stub! 
(:participants).and_return([p])" which works also.

Thanks for your help, and thanks for the extra destroy_all trick too!

Glenn

>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list