b.herring
b.herring

Reputation: 653

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.

Upvotes: 4

Views: 343

Answers (1)

smathy
smathy

Reputation: 27961

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 }

Upvotes: 2

Related Questions