RSpec 控制器规格无法更新记录

RSpec controller spec unable to update record

我有一个 Rails/RSpec 控制器规格抛出错误:

NoMethodError: undefined method `completed_set_url' for #<CompletedSetsController:0x007fcfe935c5d0>
from /Users/arelenglish/.rvm/gems/ruby-2.1.5/gems/actionpack-4.2.0/lib/action_dispatch/routing/polymorphic_routes.rb:268:in `handle_model_call'

put :update, {id: completed_set.to_param, completed_set: valid_attributes} 行是爆炸的地方。我不知道 completed_set_url 方法是什么,或者 why/where 它被调用了。

完整规格如下:

it "assigns the requested completed_set as @completed_set" do
  completed_set = CompletedSet.create! valid_attributes
  put :update, {id: completed_set.to_param, completed_set: valid_attributes}
  expect(assigns(:completed_set)).to eq(completed_set)
end

为了完整起见,这是我的控制器代码:

class CompletedSetsController < BaseController
  before_action :set_completed_set, only: [:edit, :update, :destroy]

  # POST /completed_sets
  def create
    @completed_set = CompletedSet.new(completed_set_params)
    if @completed_set.save
      redirect_to profile_path, notice: 'Successfully completed set.'
    else
      raise "Failed to save because #{@completed_set.errors.each {|e| e}}"
    end
  end

  # PUT /completed_sets/1
  def update
    respond_to do |format|
      if @completed_set.update_attributes(completed_set_params)
        format.html { redirect_to @completed_set, notice: 'Completed set was successfully updated.' }
      else
        format.html { render action: "edit" }
      end
    end
  end

  private
    # User callbacks to share common setup or constraints between actions.
    def set_completed_set
      @completed_set = CompletedSet.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def completed_set_params
      params.require(:completed_set).permit(
        :repetitions, 
        :set_number, 
        :user_id, 
        :weight, 
        :user_program_id, 
        :rpe, 
        :workout_exercise_id,
        :workout_exercise_set_id 
        )
    end

end

在您的 update 操作中从 redirect_to @completed_set 调用它。

这里的问题是,您的 update 操作在成功时重定向到 @completed_set (completed_set_url),但您的应用没有定义 show 操作该资源。

所以,在你的 config/routes.rb 文件中,定义一个显示动作(如果你的控制器是 RESTful,可能使用 resources :completed_set),然后在中定义一个 show 方法您的控制器,或将 redirect_to 更改为与您的 create 操作相同 (redirect_to profile_path)。