ruby-on-rails - RSpec 的 Rails 帖子抛出 "no route matches"

标签 ruby-on-rails ruby rspec routes

我有路线定义

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/

相关文章:

ruby-on-rails - `rails server puma` 与 `puma`

ruby - 如何合并数组组?

ruby-on-rails - factory_girl 忽略它正在创建实例的类的命名空间

ruby-on-rails - RSpec + capybara : redirect_to external page sends me back to root_path

ruby-on-rails - 不同的模型如何在 Rails 中使用相同的登录页面

ruby - 在 rspec 中定义 `after` 别名的正确方法是什么?

ruby-on-rails - Rails 仅在指定的 Controller 上强制使用 ssl

ruby-on-rails - 将数据从数据库返回到rails中的另一个页面

ruby-on-rails - 在聚合函数之前对 ActiveRecord 对象执行行操作

ruby - 如何使用redis ruby​​计算redis中的set complement操作?