views:

795

answers:

1

I want to stub just a specific model, but not only a specific object and not every instance

E.g. Given class 'Person' with attributes 'name' (string) and 'cool' (boolean). We have two models:

person_bill:
   name: bill
   cool: false

person_steve:
   name: steve
   cool: false

Now I want to stub just steve, which works alright:

p1 = people(:person_steve)
p1.stubs(:cool? => true)
assert p1.cool? #works

But if I load Model again from DB it doesn't:

p1 = people(:person_steve)
p1.stubs(:cool? => true)
p1 = Person.find_by_name p1.name
assert p1.cool? #fails!!

This works, but affects Bill as well, which shouldn't:

 Person.any_instance.stubs(:cool? => true)
 assert people(:person_bill).cool? #doesn't fails although it should

So how can I just Steve stub, but in any case? Is there a conditional any_instance like

 Person.any_instance { |p| p.name == 'Steve' }.stubs(:cool? => true)

Thanks in advance!

+2  A: 

Hi mgtng,

Why not just stub the method generating the object?

Person.stubs( :find_by_name ).
       returns( stub(:cool? => true) )

I think that's the right (and simple) answer. I'm pretty certain there is nothing like your any_instance syntax. You might find something useful in the sequence syntax:

Could you give another example of what you're looking for? Good Luck!

mixonic
well right in this case, but my actual problem is bit more tricky. I need it for a controller test where the find method is way more 'deeper' in code. But well, much test approach wasn't ok anyhow so I changed it to make it work. But still I'm curious how to make this work in anycase....
RngTng
The cure for deep code is making it shallow :-). In TDD or good unit testing, you want to avoid complex code and deep nesting. If it's hard to test, the best approach isn't a complex test for the complex code. Better to simplify/re-factor the code and write a simple test!
mixonic