2016-10-04 67 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