2012-08-22 47 views
0

我正在通過修改參數來設置用戶,而不是在表單中創建hidden_​​field。據我所知,這是一種更安全的處理羣體任務的方式。我將如何測試param在RSpec控制器測試中被修改?

def update 
    @exercise = Exercise.find(params[:id]) 

    #this is the important part 
    if params[:exercise][:log_entries_attributes].present? 
     params[:exercise][:log_entries_attributes].each do |value| 
     value[1].merge!(:user_id => current_user.id) 
     end 
    end 
    #end the important part 

    respond_to do |format| 
     if @exercise.update_attributes(params[:exercise]) 
     format.html { redirect_to_back_or_default @exercise, notice: "Exercise was successfully updated." } 
     format.mobile { redirect_to @exercise, notice: 'Exercise was successfully updated.' } 
     format.json { head :ok } 
     else 
     format.html { render action: "edit" } 
     format.mobile { redirect_to @exercise, notice: "#{@exercise.errors.full_messages.to_sentence}" } 
     format.json { render json: @exercise.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

在我的天賦,我有以下:

describe "with log_entry_attributes" do 
    it "updates log_entries_attributes and sets user" do 
    exercise = FactoryGirl.create(:exercise) 
    log_entry = FactoryGirl.build(:log_entry) 
    exercise.log_entries << log_entry 
    exercise.save 
    controller.stub(:current_user).and_return(@user) 
    put :update, :id => exercise.id, :exercise => FactoryGirl.build(:exercise, "log_entries_attributes" => {":0" => {"reps" => "5", "weight" => "5"}}).attributes.symbolize_keys 
    assigns(:exercise).log_entries.first.user.should eq(@user) 
    end 
end 

我得到undefined method user for nil:NilClass。我想我知道爲什麼我得到未定義的方法用戶。通過分配無法獲得關聯。我不知道如何測試通過current_user正確設置user_id。任何幫助?

回答

1

工作與嘲笑的對象:

exercise = double "exercise" 
Exercise.should_receive(:find).and_return(exercise) 

和測試用:

exercise.should_receive(:update_attributes).with(correct_params) 
+0

但我怎麼測試user_id是實際上得到通過CURRENT_USER設置?這就是測試應該是的,不是? –

+0

好吧,發送損壞的參數,並檢查correct_params是你所期望的。 – apneadiving

+0

哦!我現在明白了。由於它在params之外被修改,所以在update_attributes期間,它應該期望它在修改後看起來像我想要的那樣。大。我知道了!謝謝! –