2
votes

I have a rails (6.0.0) project where the api route responses are being put together with jbuilder (2.9.1). I'm coming across an error using rspec-rails (3.9.0) where I'm trying to test the controller, but it's throwing this error:

Failure/Error: render :show

     ActionView::MissingTemplate:
       Missing template api/users/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062f50>"
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062ed8>"
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062e88>"
     # ./app/controllers/api/users_controller.rb:8:in `create'
     # ./spec/controllers/api/users_controller_spec.rb:7:in `block (4 levels) in <top (required)>'
     # -e:1:in `<main>'

controllers/api/users_controller.rb:

def create
  @user = User.new(user_params)
  if @user.save
    login(@user)
    render :show
  else
    render json: @user.errors.full_messages, status: 422
  end
end

views/api/users/show.json.jbuilder:

json.partial! 'api/users/user', user: @user

routes.rb:

  namespace :api, defaults: { format: :json } do
    resources :users, only: [:create, :index, :update]

users_controller_spec.rb:

it 'validates the presence of username, password, and email' do
  post :create, params: { use_route: 'api/users', user: { username: 'username', password: 'password', email: 'email' } }
  expect(response).to have_http_status 200
end

I've looked around a ton on stackoverflow, but haven't found anything that helps with this. Not sure if it's a rails version issue or if I'm not setting something up properly. It looks like it keeps trying to find an html format file, as opposed to json, even though I set up the default format to be json in the routes.rb file under the api namespace.

Any help would be appreciated!

1

1 Answers

2
votes

I know it has been awhile since this question was posted but I would check on two things: make sure you are telling RSpec config to render views and make sure you post / get as json.

in spec/rails_helper.rb

RSpec.configure do |config|
   config.render_views = true
   # the rest of config
end

in your spec file

post :create, params: { ... }, as: :json