我在尝试在 Rspec 测试中将 JSON 形式发布到控制器操作时遇到问题:
RSpec.describe RegistrationsController, type: :controller do
context 'Adding a Valid User' do
it 'Returns Success Code and User object' do
@params = { :user => {username: 'name', school: 'school'} }.to_json
post :create, @params
end
end
end
目前我想成功触发发布请求,但总是收到此错误:
Failure/Error: post :create, @params
AbstractController::ActionNotFound:
Could not find devise mapping for path "/lnf".
我的路线设置如下:
Rails.application.routes.draw do
constraints(subdomain: 'api') do
devise_for :users, path: 'lnf', controllers: { registrations: "registrations" }
devise_scope :user do
post "/lnf" => 'registrations#create'
end
end
end
Rake 路由输出以下内容:
Prefix Verb URI Pattern Controller#Action
user_registration POST /lnf(.:format) registrations#create {:subdomain=>"api"}
lnf POST /lnf(.:format) registrations#create {:subdomain=>"api"}
那么我对同一个操作有两个声明?
经过几个小时的艰苦努力,我的测试正确通过并通过执行以下操作以 JSON 形式发布:
require 'rails_helper'
RSpec.describe RegistrationsController, type: :controller do
before :each do
request.env['devise.mapping'] = Devise.mappings[:user]
end
context 'Adding a Valid User' do
it 'Returns Success Code and User object' do
json = { user: { username: "richlewis14", school: "Baden Powell", email: "[email protected]", password: "Password1", password_confirmation: "Password1"}}.to_json
post :create, json
expect(response.code).to eq('201')
end
end
end
我的路线已恢复正常:
Rails.application.routes.draw do
constraints(subdomain: 'api') do
devise_for :users, path: 'lnf', controllers: { registrations: "registrations" }
end
end
在我的测试环境中我必须添加:
config.action_mailer.default_url_options = { host: 'localhost' }
这里的关键是:
request.env['devise.mapping'] = Devise.mappings[:user]
尚未完全确定它的作用,它是我列表中的下一个要找出的内容,但我的测试已开始运行并通过。