当我使用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 :(得分:0)
请你更改下面的参数并尝试一下吗?
let(:headers){{“ACCEPT”=&gt; “application / json”,“CONTENT_TYPE”=&gt; “application / json”}} let(:json_body){{format :: json,foo: '测试'}}
检查路线。