简体   繁体   English

我将如何测试在RSpec控制器测试中修改的参数?

[英]How would I test a param is getting modified in a RSpec controller test?

I am setting a user through modifying the params instead of creating a hidden_field in the form. 我通过修改参数来设置用户,而不是在表单中创建hidden_​​field。 As far as I understand, this is a more secure way of handling mass-assignment. 据我了解,这是处理批量分配的一种更安全的方法。

  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

In my spec I have the following: 在我的规范中,我有以下内容:

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

I get undefined method user for nil:NilClass . 我得到undefined method user for nil:NilClass I think I know why I get undefined method user. 我想我知道为什么我得到未定义的方法用户。 There's just no way to get the association through assigns. 根本没有办法通过分配获得关联。 I'm not sure how to test that the user_id is being set properly through the current_user. 我不确定如何测试通过current_user是否正确设置了user_id。 Any help? 有什么帮助吗?

Work with mocked object: 使用模拟对象:

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

and test with: 并测试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM