I can't figure out why the rspec expect to change matcher is not working, even though I replicated the logic and I am certain the code is correct.
Here's what I have:
class SubscriptionItem < ApplicationRecord
after_commit :create_customer_quotas, on: :create
def create_customer_quotas
CustomerQuotaService.create_from_subscription_item! self
end
def self.create_from_subscription_item!(subscription_item)
customer = subscription_item.customer
subscription_item.quotas.each do |quota|
CustomerQuota.find_or_create_by! quota:, subscription_item:, customer:
end
end
In my test, I have this:
expect { subscription.save! }.to change(CustomerQuota, :count).by(subscription.quotas.count)
and I get this failure:
expected `CustomerQuota.count` to have changed by 1, but was changed by 0
However, when I replicate the expect to change logic in the test like so:
count_before = CustomerQuota.count
subscription.save!
count_after = CustomerQuota.count
puts "before=#{count_before} && after=#{count_after}"
the output is:
before=0 && after=1
So it's clearly working. Why is the expect to change not working as expected?