DEV Community

Cover image for Failure/Error: render template: 'path/to/template'
Ken Obara
Ken Obara

Posted on

Failure/Error: render template: 'path/to/template'

My Rails application works for API. When I tested the codes with Rspec, I got the following error.

$ bundle exec rspec
...
Failure/Error: render template: 'path/to/template'
...
Enter fullscreen mode Exit fullscreen mode

Solutions

We can fix this problem by setting the request header for JSON. There are some solutions.

If we want to set it for each testing code, we can use format: :json

RSpec.describe MyController, type: :controller do
  it 'my test' do
    get :index, format: :json
    expect(response).to have_http_status(:ok)
  end
end
Enter fullscreen mode Exit fullscreen mode

If we want to set it for all testing codes at once, we can change config settings.

# spec/rails_helper.rb or spec/spec_helper.rb
RSpec.configure do |config|
  config.before(:each, type: :controller) do
    request.env['CONTENT_TYPE'] = 'application/json'
    request.env['HTTP_ACCEPT'] = 'application/json'
  end

  config.before(:each, type: :request) do
    if defined?(headers)
      headers['Content-Type'] = 'application/json'
      headers['Accept'] = 'application/json'
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)