【问题标题】:test missing template测试缺少的模板
【发布时间】:2013-10-16 15:13:31
【问题描述】:

尝试编写应该是一个简单的 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:

【问题讨论】:

  • 不太确定具体问题的根本原因,但我建议查看 ActiveModelSerializers gem。它可以有效地处理您在上面尝试完成的所有事情。替代方案是 Rabl(不建议)和 JBuilder(新的和改进的序列化)

标签: ruby-on-rails json rspec


【解决方案1】:

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

澄清:

这是最初发布的内容:

  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 要渲染什么,所以它会尝试为创建操作渲染默认模板。这就是Missing template comments/create 的来源。

我对@9​​87654327@ 部分的意思是:

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

【讨论】:

  • 我不明白你的更新...你想做render nothing: true吗?
  • @commentable 为零时,我错过了else 部分是什么意思?这就是为什么我想也许我在第一个if 之后错过了else。但是你这是什么意思
猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2012-04-18
  • 1970-01-01
相关资源
最近更新 更多