Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a delete association to return false

I have dealer.cars where a dealer has many cars. In my spec i want to stub dealer.cars.delete(car) to return false. However i cannot get this to work. I have currently tried:

allow_any_instance_of(Car).to receive(:delete).and_return(false)

expect(dealer.cars).to receive(:delete).with(car).and_return(false)

However in my code when running the spec it is still returning true.

like image 629
b.herring Avatar asked Oct 18 '25 11:10

b.herring


1 Answers

Assuming cars is a has_many association on the Dealer model then no, cars won't be returning an instance of Car, it'll be returning a collection instance of class Car::ActiveRecord_Associations_CollectionProxy - so if you wanted to use the allow_any_instance_of, then you'd need to use that.

But a much better way to mock a chain of calls is:

expect(dealer).to receive_message_chain(:cars, :delete) { false }
like image 189
smathy Avatar answered Oct 21 '25 01:10

smathy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!