【问题标题】:Whats the way to define a test for a Grape API?为 Grape API 定义测试的方法是什么?
【发布时间】:2014-12-06 13:38:21
【问题描述】:

我正在尝试定义一个测试环境,以便以编程方式向我的 Grape API 发出请求。

我将主 API 文件放入 /app/api/services/v1.rb 中,并在规范路径中创建了一个名为 requests 的文件夹,其中包含一个包含此内容的文件用于测试:

describe Services::V1 do
  describe "GET /v1/users/:id" do
    it "returns a user by id" do
      user = User.create!
      get "/api/users/#{user.id}"
      expect(response.body).to eq user.to_json
    end
  end
end

API 为用户资源定义了一个路径,但我有一个错误,这意味着 Servicesnamespace 是“未初始化的常量服务 (NameError)”

我已将 config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/ 添加到 spec_helper 中,但我认为我误解了与此相关的 Grape 文档。

“您可能希望您的 API 代码进入 app/api - 您可以匹配 通过在 spec/spec_helper.rb 中添加以下内容,在规范下进行布局。

RSpec.configure 做 |config|配置.include RSpec::Rails::RequestExampleGroup,类型::请求,文件路径: /spec/api/ 结束”

感谢任何帮助使事情正常进行。我是这个技术设置的新手。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 api rspec grape


    【解决方案1】:

    您需要测试资源而不是 api 版本。

    describe "ExampleApi::V1::Regions" do
    
      describe "GET /api/v1/regions/{id}" do
        context "without data" do
          it "should return a status code 404" do
            get "/api/v1/regions/100000000", nil, { 'Authorization' => "Bearer #{token.token}"}
            expect(response.status).to eq 404
          end
    
          it "should return an empty array" do
            get "/api/v1/regions/100000000", nil, { 'Authorization' => "Bearer #{token.token}"}
            expect(json['error']['code']).to eq(404)
          end
        end
    
        context "with data" do
          it 'returns a status code 200' do
            get "/api/v1/regions", nil, { 'Authorization' => "Bearer #{token.token}"}
            expect(response.status).to eq 200
          end
    
          it 'returns a region' do
            region1 = Fabricate(:region)
            get "/api/v1/regions/#{region1.id}", nil, { 'Authorization' => "Bearer #{token.token}"}
            expect(json["id"]).to eq(region1.id)
          end
        end
      end
    
    end
    

    在此示例中,如果您使用身份验证(在本例中为 Oauth2),则使用 Authorization 标头。

    还有一个helper或者json,你可以在support文件夹中创建一个文件:

    module Requests
      module JsonHelpers
        def json
          @json ||= JSON.parse(response.body)
        end
      end
    end
    

    在 rails_helper.rb 添加:

    # Just if the tests are in spec/api folder
    config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/
    

    【讨论】:

      【解决方案2】:
      1. 如果您在 rails_helper.rb 中添加 config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/,这意味着您应该将您的 api 规范放入 /spec/api/,而不是 /spec/requests/

      2. 你应该在你的/spec/api/services/v1/regious_spec.rb中添加require 'rails_helper'

      【讨论】:

        猜你喜欢
        • 2020-12-25
        • 2013-06-08
        • 2015-02-01
        • 2013-10-17
        • 2012-01-08
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多