使用FactoryGirl时,Rspec测试失败

时间:2010-10-28 14:06:46

标签: rspec factory-bot

我第一次使用FactoryGirl,并为以下控制器代码设置了测试


# 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是测试,看到该方法将所选的(selected:boolean)属性值更新为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

我发现我的更改会在我测试之前回滚。我的意思是update_attributes被调用并且它将select属性的值更新为true,但是在我的测试中它表示answer.selected字段没有更新。

想要一些帮助吗?

1 个答案:

答案 0 :(得分:2)

尝试在put

之后的规范中添加此内容
@answer.reload

这将从数据库中获取列的当前值,并更新@answer的属性。它也会返回对象,因此您可以保存一行并放置:

@answer.reload.should be_selected