测试缺少模板

时间:2013-10-16 15:13:31

标签: ruby-on-rails json rspec

尝试编写应该是简单的RSpec测试,并设置我的创建操作以呈现JSON,如下所示:

require 'spec_helper'

describe CommentsController do

  let(:valid_attributes) do
    {
        title: 'First Comment', comment_text: 'LoremIpsum', commentable_id: 1,
        user_id: 1, entered_by: 'john', last_updated_by: 'doe'
    }
  end

  context 'JSON' do
    describe 'POST create' do
      describe 'with valid params' do
        it 'creates a new Comment' do
          json = {:format => 'json', :comment => valid_attributes}
          post :create, json
        end

        it 'assigns a newly created comment as @comment' do
          json = {:format => 'json', :comment => valid_attributes}
          post :create, json
          assigns(:comment).should be_a(Comment)
          assigns(:comment).should be_persisted
        end
      end
    end
  end
end

但是我得到以下输出:

ActionView::MissingTemplate: Missing template comments/create, application/create with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}. Searched in:

1 个答案:

答案 0 :(得分:0)

else为零时,你错过了@commentable部分。这将尝试渲染默认模板!

澄清:

这是最初发布的内容:

  def create
    if @commentable
      @comment = @commentable.comments.new(comment_params)
      if @comment.save
        render json: @comment, status: :created
      else
        render json: @comment.errors, status: :unprocessable_entity
      end
    end
  end

@commentablenil的情况下,没有任何内容告诉rails要呈现的内容,因此它将尝试呈现create动作的默认模板。这是Missing template comments/create的来源。

我对else部分的意思是:

  def create
    if @commentable
      [...]
    else
      head 404
    end
  end