Another approach is to refactor your code to allow simple unit tests. This way, your code approaches the upper limit of how much code I would put in the callback:
after_initialize do if self.country_id.nil? self.country_id = self.user.main_address.country_id || Country.first.id end end
If it grew much more, I would extract it into a method and reduce your callback to a method call:
after_initialize :init_country_id def init_country_id if self.country_id.nil? self.country_id = self.user.main_address.country_id || Country.first.id end end
The bonus here is that testing init_country_id becomes yet another unit test method at the moment ... there is nothing special about this.
Now that you have a unit behavior test, you can also verify that it is being called if you have doubts. (Something after_initialize :init_country_id as simple as after_initialize :init_country_id does not require testing calls, IMO)
You can use gem shoulda-callback-matchers to verify that your callbacks actually run, as intended:
it { is_expected.to callback(:init_country_id).before(:initialize) }
source share