Home > Software engineering >  Testing an update operation in RSpec, evaluates to true, but test fails?
Testing an update operation in RSpec, evaluates to true, but test fails?

Time:11-30

I have this test:

it "saves the notification id in the referral for future reference" do
  expect { subject.perform(*args) }
    .to change(referral, :notification_id).from(nil).to(customer_notification_delivery.id)
end

And the code that it runs on top is:

if notification.present?
  referral.update(friend_customer_notification_delivery_id: notification.id)
end

I added a few debug messages, to check on them after firing the test, to ensure that this condition was being met, and the code was being run, and I got true for both

  p notification.present?
  p referral.update(friend_customer_notification_delivery_id: customer_notification_delivery.id)

Anything I am missing? Why the update returns true, but the value is not getting updated on the test?

The output I get: expected #notification_id to have changed from nil to 5, but did not change

CodePudding user response:

referral in your test and referral in your object-under-test are two different objects, I'm willing to bet. Changes to one do not affect the other. referral in the test does not magically pull up updates from the related database record made by some other code.

I normally do it like this

it "saves the notification id in the referral for future reference" do
  expect { subject.perform(*args) }
    .to change{ referral.reload.notification_id }.from(nil).to(customer_notification_delivery.id)
end
  • Related