2016-10-04 97 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和嘗試?

設(:報頭){{ 「ACCEPT」=> 「應用/ JSON」, 「CONTENT_TYPE」=> 「應用程序/ JSON」}}讓(:json_body){{格式::JSON,FOO : 'test'}}

查詢路線了。

+0

感謝您的回答。然而這不起作用;發生語法錯誤。 – Tosh