Stack: Rails 3.0.7, Mongoid 2.2.5, RSpec 2.11.0, RR 1.0.4
I have a Subscription model that looks like this:
class Subscription
include Mongoid::Document
embeds_many :addons
after_save :update_feature_policy!
def update_feature_policy!
puts "Updating feature policy!"
end
end
I have a spec that looks like this:
it "should update FeaturePolicy when adding an addon" do
puts "Starting spec"
mock(subscription).update_feature_policy! { true }
subscription.addons << user_addon
puts "Finished spec"
end
The spec fails, but I see this output in the console:
Starting spec
Updating feature policy!
Finished spec
Failure/Error: mock(subscription).update_feature_policy! { true }
RR::Errors::TimesCalledError:
update_feature_policy!()
Called 0 times.
Expected 1 times.
What's causing the mock object not to capture the method call and pass the spec?
It appears that the callback was re-finding the record and creating a separate instance of subscription (thus not hitting the mock object). I'm not sure why - seems like it's not very performant - but I found a workaround:
it "should update FeaturePolicy when adding an addon" do
puts "Starting spec"
mock.instance_of(Subscription).update_feature_policy! { true }
subscription.addons << user_addon
puts "Finished spec"
end
This checks for update_feature_policy!
being called on any instance of Subscription
. Not great, but for my purposes it works.
If anyone can answer why this is happening or provide a better solution, please do.