Rails Test & Mocha: How to stub specific model - conditional any_instance?
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? I开发者_JS百科s there a conditional any_instance like
Person.any_instance { |p| p.name == 'Steve' }.stubs(:cool? => true)
Thanks in advance!
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:
- http://mocha.rubyforge.org/classes/Mocha/API.html#M000005
Could you give another example of what you're looking for? Good Luck!
精彩评论