Thursday, July 24, 2008

Remember to reload your associations in your tests

Save time by reloading your associations when using RSpec.

    1 # your_object.rb
2 class YourObject < ActiveRecord::Base
3 def your_method
4 self.your_association << TestObject.new
5 end
6 end
7
8 # your_object_spec.rb
9 it "should test your_method" do
10 lambda { your_object.your_method }.should change(your_object.your_association, :size) # => no change, test fails....
11 end
12


Just put a reload after your association call:

    1 # your_object_spec.rb
2 it "should test your_method" do
3 lambda { your_object.your_method }.should change(your_object.your_association.reload, :size) # => association reloads and the test succeeds
4 end

No comments: