RSpec返回404;使用JSON数据发布到子域

时间:2016-09-29 05:31:41

标签: ruby-on-rails json ruby rspec

我试图在Request Rspec中发送原始JSON。 (因为我在Controller Rspec中尝试过,但是在rails 4.2中没有解析JSON数据。) 我还设置了子域 api

我总是得到404

  describe "POST #create" do
    let(:json_body) do
      '{"foo":"foo_value", "bar":"bar_value", "baz":"baz_value"}'
    end
    it "returns not acceptable to non json content-type request" do
      post "/subscriptions" , json_body, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
    end

有任何解决此问题的想法吗?

更新

config/routes.rb

require 'api_constraints'

Rails.application.routes.draw do
  namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/'  do
    scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
      resources :subscriptions, only: [:index, :new, :create]
    end
  end

end

UPDATE2

我设置host! 'api.localhost.local',然后它工作。 参考:https://github.com/rspec/rspec-rails/issues/1662 参考2:http://www.screencast.com/t/nyZ2jKQi

Rspec.configure do |config|
  config.before(:all, type: :request) do
    host! 'api.lvh.me'
  end
end

另外我想知道为什么一旦我使用子域设置这样的路由,它会将<subdomain_name>.localhost.local:3000路由为默认值?

1 个答案:

答案 0 :(得分:0)

require 'rails_helper'

RSpec.describe Api::V1::SubscriptionsController, type: :request do
  let(:json_body) do
    '{:foo: 12, bar: 33}'
  end
  it "returns not acceptable to non json content-type request" do
    host! 'api.lvh.me' # <= This is needed because 'api' is the subdomain.
    headers = {
      "ACCEPT" => "application/json",     # This is what Rails 4 accepts
      'CONTENT_TYPE' => 'application/json'
    }

    post "/subscriptions", json_body.to_json ,headers
  end
end