gpt4 book ai didi

ruby-on-rails - 设置接受 : to application/json for controller specs

转载 作者:行者123 更新时间:2023-12-01 05:12:04 24 4
gpt4 key购买 nike

为 json api 编写规范,路由默认只接受 json 请求,如下所示:

Rails.application.routes.draw do
namespace :api, default: { format: 'json' } do
namespace :v1 do
resources :users, only: [:create]
end
end
end

我不断收到以下错误:
Failure/Error: post :create, json
ActionController::UrlGenerationError:
No route matches {:action=>"create", :company_name=>"Wilderman, Casper and Medhurst", :controller=>"api/v1/users", :email=>"lillie_prohaska@example.com", :password=>"difdcbum5q", :username=>"gielle"}

传统上,为了解决这个错误,我在请求上设置了 CONTENT_TYPE 和 HTTP_ACCEPT,以便它通过 json 格式要求。

我的规范是这样写的:
describe Api::V1::UsersController do

before :each do
@request.env['HTTP_ACCEPT'] = 'application/json'
@request.env['CONTENT_TYPE'] = 'application/json'
end

describe "POST#create" do
context "with valid attirbutes" do
let(:json) { attributes_for(:user) }

it "creates a new user" do
expect{ post :create, json }.to change{ User.count }.by(1)
end

it "returns status code 200" do
post :create, json
expect(response.status).to be(200)
end

it "should contain an appropriate json response" do
post :create, json
user = User.last
json_response = {
"success" => true,
"id" => user.id.to_s,
"auth_token" => user.auth_token
}
expect(JSON.parse(response.body)).to eq (json_response)
end
end
end
end

我也试过用 { format: 'json' } 添加一个哈希值这也让我失望。

根据对以下问题的已接受答案的评论,设置请求环境 header 将不再适用于 rspec 3:

Set Rspec default GET request format to JSON

这将如何在 Rails 4.1.1 的 rspec 3 中实现?

谢谢!

最佳答案

这是我在这里做的:

  [:xml, :json].each do |format|

describe "with #{format} requests" do
let(:api_request) { { :format => format } }
describe "GET 'index'" do
before :each do
api_request.merge attributes_for(:user)
end
it 'returns HTTP success' do
get :index, api_request
expect(response).to be_success
end
end
end

关于ruby-on-rails - 设置接受 : to application/json for controller specs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com