3

我正在使用rspec_api_documentation在 Rails 4 中构建一个 API,这给我留下了深刻的印象。选择使用 DoorKeeper 来保护我的端点后,我成功地从控制台测试了这一切,并让它正常工作。

我现在遇到的困难是如何指定它并存根令牌。

DoorKeeper 的文档建议使用以下内容:

describe Api::V1::ProfilesController do
  describe 'GET #index' do
    let(:token) { stub :accessible? => true }

    before do
      controller.stub(:doorkeeper_token) { token }
    end

    it 'responds with 200' do
      get :index, :format => :json
      response.status.should eq(200)
    end
  end
end

但是,我已经根据 rspec_api_documentation 编写了验收测试。这是projects_spec.rb我写的:

require 'spec_helper'
require 'rspec_api_documentation/dsl'

resource "Projects" do
  header "Accept", "application/json"
  header "Content-Type", "application/json"

  let(:token) { stub :accessible? => true }

  before do
    controller.stub(:doorkeeper_token) { token }
  end

  get "/api/v1/group_runs" do
    parameter :page, "Current page of projects"

    example_request "Getting a list of projects" do
      status.should == 200
    end
  end
end

当我运行测试时,我得到以下信息:

undefined local variable or method `controller' for #<RSpec::Core

我怀疑这是因为它不是明确的控制器规范,但正如我所说,我宁愿坚持这种 rspec_api_documentation 测试我的 API 的方式。

肯定有人必须这样做吗?还有另一种方法可以存根令牌吗?

提前致谢。

4

2 回答 2

3

我遇到了同样的问题,我使用指定的令牌手动创建了访问令牌。通过这样做,我就可以在 Authorization 标头中使用我定义的令牌:

resource "Projects" do
  let(:oauth_app) { 
    Doorkeeper::Application.create!(
      name: "My Application", 
      redirect_uri: "urn:ietf:wg:oauth:2.0:oob" 
    ) 
  }
  let(:access_token)  { Doorkeeper::AccessToken.create!(application: oauth_app) }
  let(:authorization) { "Bearer #{access_token.token}" }

  header 'Authorization', :authorization

  get "/api/v1/group_runs" do
    example_request "Getting a list of projects" do
      status.should == 200
    end
  end
end
于 2014-08-14T01:16:05.257 回答
2

我不建议在 rspec_api_documentation 验收测试中删除 DoorKeeper。RAD 的好处之一是可以查看它生成的示例中的所有标头。如果您要删除 OAuth2,那么阅读文档的人在尝试创建客户端时将看不到任何 OAuth2 标头。

我也不确定是否可以很好地做到这一点。RAD 与 Capybara 功能测试非常相似,快速搜索使其看起来很难做到。

RAD 有一个OAuth2MacClient你可以使用的,在这里

require 'spec_helper'

resource "Projects" do
  let(:client) { RspecApiDocumentation::OAuth2MACClient.new(self) }

  get "/api/v1/group_runs" do
    example_request "Getting a list of projects" do
      status.should == 200
    end
  end
end
于 2013-10-25T12:27:41.623 回答