Rspec失败 - render_template:new expecting<“new”>但使用< []>进行渲染

时间:2017-01-17 16:44:24

标签: ruby-on-rails rspec

运行rspec时出现以下错误。真的可以帮到这里!我不确定嵌套资源或ajax调用是否会导致rspec失败。

1) GoalsController GET #new renders the :new template
  Failure/Error: expect(response).to render_template :new
    expecting <"new"> but rendering with <[]>
  # ./spec/controllers/goals_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

以下是我的代码,如下所示。

的routes.rb

Rails.application.routes.draw do

  resources :strategies, :only => :none do
    resources :goals
  end

  resources :goals, :only => :none do
    resources :objectives
  end
end

goals_controller.rb

class GoalsController < ApplicationController
  respond_to :html, :js

  def new
    @strategy = Strategy.find(params[:strategy_id])
  end

  def index
    @strategy = Strategy.find(params[:strategy_id])
  end

  def create
    @user = User.find(current_user.id)
    @strategy = Strategy.find(params[:strategy_id])
    @goal = @strategy.goals.create(goal_params.merge(
                                      start_date: @strategy.start_date,
                                      end_date: @strategy.end_date,
                                      created_by: @user.id))
    respond_to do |format|
      format.js { }
    end
  end

  private
    def goal_params
      params.require(:goal).permit(:name, :budget)
    end
end

goals_controller_spec.rb

require 'rails_helper'

RSpec.describe GoalsController, type: :controller do
  describe 'GET #new' do
    it "renders the :new template" do
      get :new, strategy_id: 2
      expect(response).to render_template :new
    end
  end

end

1 个答案:

答案 0 :(得分:0)

像Sergey Sokolov在评论中建议的那样,尝试删除所有:only => :none 在路线中。

resources会为所有CRUD操作生成路由,:only => :none基本上是说您根本不希望它生成。