2016-10-04 9 views
0

Rspec(要求タイプ)のJSONパラメーター、 パラメーターを渡したときの問題は、コントローラーに正しく渡されません。 (現実世界では、動作しています)RoR上のRspec; JSON形式のパラメーターを渡す(パラメーターが空です)

アイデアはありますか?

controllers/api/v1/subscriptions_controller.rb

module Api 
    module V1 
    class SubscriptionsController < ApplicationController 
     # TODO: Better user inheritance 

     skip_before_action :verify_authenticity_token # Disable CSRF to enable to function as API 
     before_action :restrict_content_type 
     before_action :restrict_accept_header 
     before_action :load_plans 

     respond_to :json 

     # NOTE: This block is used when you put unrelated values 
     rescue_from(ArgumentError) do |e| 
     render json: { error: e.message }, states: :bad_request 
     end 

     rescue_from(ActionController::ParameterMissing) do |e| 
     error = {} 
     error[e.param] = ['parameter is required'] 
     response = { errors: [error] } 
     render json: response, status: :unprocessable_entity 
     end 


     def create 
     binding.pry #<= `params` is empty within Testing. 
     end 

     private 

     def restrict_content_type 
     render json: { msg: 'Content-Type must be application/json' }, status: 406 unless request.content_type == 'application/json' 
     end 

     def restrict_accept_header 
     render json: { msg: 'Accept-Header must be application/json' }, status: 406 unless request.headers['Accept'] =~ /json/ 
     end 

     def load_plans 
     @plans = Plan.where(published: true).order('amount') 
     end 

     def foo_params 
     params.require(:foo) 
     end 


     # NOTE: returns validation errors with JSON API format 
     def jsonapi_errors(model) 
     errors = [] 
     model.errors.messages.each do |attr, message| 
      errors.push(title: 'Invalid Attribute', detail: "#{attr.capitalize}: #{message[0]}") 
     end 
     errors 
     end 
    end 
    end 
end 

spec/requests/subscription_request.spec

require 'rails_helper' 

RSpec.describe Api::V1::SubscriptionsController, type: :request do 
    describe 'General API test' do 

    before(:each) do 
     host! 'api.lvh.me' 
    end 

    let(:headers) do 
    { 
     'ACCEPT' => 'application/json',  # This is what Rails 4 accepts 
     'CONTENT_TYPE' => 'application/json' 
    } 
    end 
let(:json_body) do 
    {format: :json, foo: 'test'} # Invalid request 
end 



    it 'returns 200 to valid json' do 

     post '/subscriptions', json_body, headers 
     binding.pry 
     expect(response.status).to eq 200 
    end 

答えて

0

あなたは以下のようにあなたのparamsを変更し、それを試してみてくださいことはできますか?

LET(:ヘッダ){{=> "アプリケーション/ JSON" を "ACCEPT"、 "CONTENT_TYPE" => "アプリケーション/ JSON"}}せ(:json_body){{フォーマット:JSON、FOO : 'test'}}

経路も確認してください。

+0

回答ありがとうございます。しかし、これはうまくいきません。構文エラーが発生します。 – Tosh

関連する問題