I am working in Rails 2.0 and I have the following functional test.
class VotesControllerTest < ActionController::TestCase def test_should_create_vote assert_difference('Vote.count') do post :create, {:vote => {:vote_value => 5, :user_id => users(:nick).id, :entry_id => entries(:BmxEntry).id}}, :user_id => users(:nick).id end assert_redirected_to vote_path(assigns(:vote)) end end
This tests the :create action of the vote controller which looks like this. def create @vote = Vote.new(params[:vote])
respond_to do |format| if @vote.save
# Update the entry vote count and vote total columns @vote.entry.vote_count ||= 0 @vote.entry.vote_total ||= 0 @vote.entry.vote_count += 1 @vote.entry.vote_total += @vote.vote_value @vote.entry.update_attribute(:vote_count, @vote.entry.vote_count) @vote.entry.update_attribute(:vote_total, @vote.entry.vote_total)
flash[:notice] = 'Vote was successfully created.' format.html { redirect_to(@vote)} format.xml { render :xml => @vote, :status => :created, :location => @vote } else format.html { render :action => "new", :layout => false } format.xml { render :xml => @vote.errors, :status => :unprocessable_entity } end end end
As you can see, after the vote is created the vote's parent, entry, is updated to reflect the new vote. All the associations are set up where entry has_many :votes and vote belongs_to :entry. This code works just fine when working in development, but the test fails giving this error:
NoMethodError: You have a nil object when you didn't expect it! The error occurred while evaluating nil.value
If I comment out the two following lines that update_attribute then the test succeeds.
# @vote.entry.update_attribute(:vote_count, @vote.entry.vote_count) # @vote.entry.update_attribute(:vote_total, @vote.entry.vote_total)
I am not sure what is causing this error, I checked and @vote.entry is set and entry attributes are available. Any ideas on what may be causing this.