【问题标题】:rails json.jbuilder api with rspec -> ActionView::MissingTemplaterails json.jbuilder api with rspec -> ActionView::MissingTemplate
【发布时间】:2020-03-03 14:08:17
【问题描述】:

我有一个 rails (6.0.0) 项目,其中 api 路由响应与 jbuilder (2.9.1) 放在一起。我在尝试测试控制器时使用 rspec-rails (3.9.0) 遇到错误,但它抛出了这个错误:

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

我在 stackoverflow 上看了很多遍,但没有找到任何对此有帮助的东西。不确定这是否是 Rails 版本问题,或者我没有正确设置某些东西。看起来它一直在尝试查找 html 格式文件,而不是 json,即使我在 api 命名空间下的 routes.rb 文件中将默认格式设置为 json。

任何帮助将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    我知道这个问题发布已经有一段时间了,但我会检查两件事:确保您告诉 RSpec config 呈现视图并确保您发布/获取为 json。

    在规范/rails_helper.rb 中

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

    在您的规范文件中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多