Reputation: 8303
When I am testing for a particular project I create a new instance of an ActiveRecord object using
ObjectType.new(parameters)
This instantiation in RSpec 3.3 (the latest version) calls the after_save callback within that model though. This behavior does not match what actually happens in the development environment and what I expect when that new instance in memory is created. Additionally if I do a binding.pry on the test that this is ran on I can examine the database and in fact there is a persisted object in the database that is created by RSpec instead of just using the in memory object.
Why is this behavior occurring and how should I fix it?
UPDATE:
So it appears that if you have a dependency object that relies on the in memory ActiveRecord object and then that object is saved to the database, the in memory object will also be saved.
For example.
obj = ObjectType.new(parameters)
DependencyObject.create(relies_on: obj)
The obj
object will be persisted to the database first and then the DependencyObject will be saved.
Upvotes: 0
Views: 483
Reputation: 8303
So it appears that if you have a dependency object that relies on the in memory ActiveRecord object and then that object is saved to the database, the in memory object will also be saved.
For example.
obj = ObjectType.new(parameters)
DependencyObject.create(relies_on: obj)
The obj
object will be persisted to the database first and then the DependencyObject
will be saved. This can lead to very strange callback behavior if you have a callback on obj
on after_create or something it will get called at the execution of the save for DependencyObject
and then the save for the other object will occur. Can be very frustrating.
Upvotes: 0