Rspec测试发布为json

时间:2015-03-10 13:33:12

标签: ruby-on-rails ruby json rspec

我在尝试将jSON发布到我的rspec测试中的控制器操作时遇到问题

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"}

所以我对同一个动作有2个声明?

任何人都可以对此有所了解

由于

1 个答案:

答案 0 :(得分:0)

好的,经过几个小时的努力,我的测试通过正确并通过以下方式发布为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: "richlewis14@gmail.com", 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]

尚未完全确定它的作用,它在我的列表中的下一个要查找,但我的测试开始运行并通过