RSPEC无法呈现JSON.jbuilder文件(缺少模板错误)

时间:2015-04-20 23:24:17

标签: ruby-on-rails json rspec controller jbuilder

我正在使用RSpec测试我的rails应用程序,并正在测试控制器。具体来说,我正在尝试渲染我的jobs.json.jbuilder视图文件。

我的控制器

class CustomersController < ApplicationController
  before_action :authenticate_member!
  before_action :set_customer


def jobs
    @jobs = @customer.jobs
end

我的相应观点位于: views/customers/jobs.json.jbuilder

我的RSpec测试是:

describe "GET job" do 
    it "renders the jobs view" do 
    get 'jobs', {id: @customer.id}, {format: :json}
    expect(response).to render_template("customers/jobs.json.jbuilder")
    end
end

然而,我一直得到的错误是:

     Failure/Error: get :jobs, {id: @customer.id}, {format: :json}
     ActionView::MissingTemplate:
       Missing template customers/jobs, application/jobs with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :slim]}. Searched in:
         * "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007fa219178f78>"
     # ./spec/support/engine_controller.rb:25:in `process_action'
     # ./spec/support/engine_controller.rb:3:in `get'
     # ./spec/controllers/customers_controller_spec.rb:31:in `block (3 levels) in <top (required)>'

注意:如果我制作了一个jobs.html.erb文件,那么这个错误就会消失,(它会呈现jobs.html.erb文件) - 所以我的问题是如何呈现.json.jbuilder观点?

这是我的spec/support/engine_controller文件:

 module EngineController
   def get(action, parameters = nil, session = nil, flash = nil)
           process_action(action, parameters, session, flash, "GET")
   end 

    private
       def process_action(action, parameters = nil, session = nil, flash =       nil, method = "GET")
        parameters ||= {}
        process(action, method, parameters.merge!(:use_route => :my_engine_name), session, flash, )
      end

2 个答案:

答案 0 :(得分:2)

使用以下语法解决了问题:

describe "GET job" do 
  it 'renders the jobs view' do 
    get 'jobs', { id: @customer.id, format: :json }
    expect(response).to render_template("customers/jobs")
  end
end

答案 1 :(得分:0)

这是一个很晚的答案,但是,对于那些仍在问这个问题的人...

默认情况下,要渲染json.jbuilder,您应该将其放在routes.rb上

在这种情况下...

resources :costumers, defaults: { format: :json }, only: [...] do
  get 'job', to: 'costumers#job'
end