Using ActiveRecord’s Reload Method to Keep Attributes Current
A common occurrence for testing is creating an object as a variable inside your test file, then testing if a method correctly modifies this value. If you were to directly check the local object after modifying it, you may be surprised to see that it has the same attributes as it did when it was created.
No, your method isn’t necessarily failing, you are just running into the issue of referencing your in memory variable, local to the test file, instead of the database value you successfully changed. To avoid this issue, we will need to use the reload method.
What is Reload?
The reload method is an ActiveRecord base method that is available to all classes that inherit from ActiveRecord::Base. What this means is that any normally constructed models will have access to this method.
Because this is available to almost all models, we are able to use it on any model we will be testing. What this method does is reach out to the database and grab the most current attributes for the specified model. It reloads what is stored in memory for that object.
This is great because it prevents asserting on stale, in memory objects that would cause your tests to fail. Rest easy that you won’t be testing yesterday’s user_profile.
How Does Reload Work?
Let’s look at a quick example to get an understanding of reload:
Here we see that we are using factory_bot to create an instance of our user class with certain attributes. Below that we want to test the update_name method which should change our user’s name to “Stephen”. It’s not super useful, but that’s just how business requirements go sometimes.
We call our method on our model and then want to assert that the name has been updated. If we don’t use reload, we can expect to see the test fail as it will load the in memory user.first_name value of “Fred”. However by attaching reload to our object, we will have the updated value and see that our user is indeed now names “Stephen”.
Conclusion
While we looked at an application for using reload in testing, it is not limited to tests. You can use reload for many business logic functions including reloading the attributes of a cart among others. Let me know in the comments how you plan to use reload in your next app or feature!
Notes
https://apidock.com/rails/ActiveRecord/Base/reload
https://everydayrails.com/2015/04/05/rspec-assigns-rails-testing.html