我正在设置用户修改参数而不是在表单中创建hidden_field。据我了解,这是一种更安全的处理质量分配方式。
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是否正确设置。有什么帮助吗?
答案 0 :(得分:1)
使用模拟对象:
exercise = double "exercise"
Exercise.should_receive(:find).and_return(exercise)
并测试:
exercise.should_receive(:update_attributes).with(correct_params)