2014-10-11 41 views
2

我試圖定義一個測試環境,以編程方式向我的Grape API發出請求。爲葡萄API定義測試有什麼方法?

我的主要API文件到/app/api/services/v1.rb和我創建了一個名爲請求到規範路徑與此內容進行測試文件夾:

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是

我添加config.include的RSpec ::導軌:: RequestExampleGroup,鍵入「未初始化的常量服務(NameError)」:要求,file_path:/ spec/api /進入spec_helper,但我認爲我誤解了與之相關的Grape doc。

「您可能希望API代碼進入應用程序/ API - 您可以通過添加在規格以下/ spec_helper.rb下規範匹配 佈局

RSpec.configure做|配置|。 config.include 的RSpec的Rails :: :: RequestExampleGroup,類型:請求,FILE_PATH: /規格/ API /結束」

任何幫助,使事情的工作表示讚賞。我是這個技術設置的新手。

回答

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)的情況。如果您在rails_helper添加config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec/api/

# Just if the tests are in spec/api folder 
config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/ 
0
  1. 還有一個幫手或JSON,您可以創建支持文件夾中的文件:rails_helper.rb附加

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

    .rb,這意味着你應該把你的API規範放在/spec/api/而不是/spec/requests/

  2. 你應該在你/spec/api/services/v1/regious_spec.rb

添加 require 'rails_helper'