我是第一次与 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

我的规范进行了测试,以查看该方法是否将所选答案的值(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 字段未更新。

需要帮助吗?

有帮助吗?

解决方案

尝试在规范中添加此内容之后 put:

@answer.reload

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

@answer.reload.should be_selected
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top