views:

15

answers:

1

I am working with FactoryGirl for the first time and have set up my tests for the following controller code


# PUT method
 def chosen    
    answer = Answer.find(params[:id])    
    if answer.update_attributes({:selected => true})
      respond_to do |format|
        format.html {
          flash[:notice] = "Success"
          redirect_to question_url(answer.question)
        }

        format.js { render :text => "Success" }
      end     
    end
  end

My Spec is tests to see that the method updates the value of the selected (selected:boolean) attributed for an answer to true.


require 'spec_helper'

describe AnswersController do
  integrate_views
  before(:each) do        
    @user = Factory.create(:user, :id => 1)
    @answer = Factory.create(:answer, :id => 1)
    @question = Factory.create(:question, :id => 1)
    User.stub!(:find).and_return(@user)
    @answer.stub!(:question).and_return(@question)
  end

  it "should use AnswersController" do
    controller.should be_an_instance_of(AnswersController)
  end

  describe "GET '/chosen'" do
    describe "mark as chosen when no answer is chosen" do            

      it "should mark a given answer as chosen" do
        #@answer.should_receive(:update_attributes!).and_return(true)
        put :chosen, :id => @answer.id
        @answer.should be_selected
      end


    end    
  end
end

What I find is my changes get rolled back before I can test it. What I mean is the update_attributes does get called and it updates the value of the select attribute to true, but in my tests it says the answer.selected field is not updated.

Will like some help?

+1  A: 

Try adding this in the spec after the put:

@answer.reload

This fetches the current value of the columns from the database and updates the attributes of @answer. It returns the object as well, so you can save a line and put:

@answer.reload.should be_selected
zetetic