我有路线定义
post '/session/create' => 'sessions#create', as: 'create_session'
Controller
class SessionsController < ApplicationController
respond_to :json
skip_before_filter :verify_authenticity_token, :only => :create
def create
# do some staff
end
end
如果我使用 RestConsole 发送帖子请求 - 它的工作原理应该如此,但是如果我尝试从 RSpec 测试发送帖子(如下所示) - 它会抛出异常。
require 'spec_helper'
describe SessionsController do
let(:user_data_to_post) { FactoryGirl.attributes_for :user }
let(:user) do
mock_model User
end
describe 'create new session should be successful' do
before do
post(create_session_path, user_data_to_post.to_json,
{'HTTP_CONTENT_TYPE' => 'application/json'})
end
it "should call search_by_email of User model" do
User.should_recive(:search_by_email).with(user_data_to_post[:email])
end
end
end
错误信息:
Failure/Error: post(create_session_path, user_data_to_post.to_json,
ActionController::UrlGenerationError:
No route matches {:HTTP_CONTENT_TYPE=>"application/json", :controller=>"sessions", :action=>"/session/create"}
# ./spec/controllers/sessions_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
最佳答案
尝试:
post :create, user_data_to_post, format: :json
首先,post
方法需要您传递给初始describe
的 Controller 上的操作名称。由于您传递了路径,因此它将整个路径视为操作名称,这显然没有被路由。
其次,post
方法签名位于post(action_name, raw_post_data(仅在字符串时分配), params=nil, session=nil, flash=nil)
行中(事实上,它是 post(action_name, *args)
但这就是处理这些参数的方式。正因为您想修改 header ,您需要直接在请求上执行此操作:
@request['HTTP_CONTENT_TYPE'] = 'application/json'
或传递format: :json
以及参数
关于ruby-on-rails - RSpec 的 Rails 帖子抛出 "no route matches",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23350894/