Tip: Reloading ActiveRecord Instances
When writing unit tests in Rails, I’ll often make a change to an ActiveRecord instance, requiring a reload for the next assertion to pass (oversimplified):
context "A new group" do setup do @group = Factory(:group) end context "with an added entry" do setup do @entry = Factory(:entry, :title => "WEB", :group => @group) @group.reload end should "add an entry to the group" assert @group.entries.include?(@entry) end end end
Instead of calling #reload on all the affected objects, I’ve found it useful to include a simple helper method that, when called, reloads any in-scope ActiveRecord instances:
class Test::Unit::TestCase private def reload_activerecord_instances self.instance_variables.each do |ivar| if ivar.is_a?(ActiveRecord::Base) && ivar.respond_to?(:reload) ivar.reload end end end end
This has proven especially helpful when I’m handling several ActiveRecord objects and need to update them all at once. Cleaner, less repetitive code.
Technology