加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 设置Accept:to application / json for contr

发布时间:2020-12-17 02:06:38 所属栏目:百科 来源:网络整理
导读:为json api编写规范,默认路由只接受json请求,如下所示: Rails.application.routes.draw do namespace :api,default: { format: 'json' } do namespace :v1 do resources :users,only: [:create] end endend 我一直收到以下错误: Failure/Error: post :crea
为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’}添加哈希,这也让我失望了.

根据对下面问题的接受答案的评论,设置请求环境标题将不再适用于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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读