简体   繁体   English

如何为需要用户身份验证的API构造Rspec请求测试

[英]How to structure Rspec Request tests for APIs requiring user authentication

I am working on an API for an app. 我正在为应用程序开发API。 I'm trying to write rspec request tests for routes that require parameters, but also belong to users and I normally requires the JWT token to access. 我正在尝试为需要参数但也属于用户的路由编写rspec请求测试,并且通常需要JWT令牌访问。

For example, how would I write a spec for testing the route POST /stocklist/:stocklist_id/balance/show 例如,我将如何编写规范以测试路线POST /stocklist/:stocklist_id/balance/show

For that I would need a user who also has a stocklist. 为此,我需要一个也有库存清单的用户。 I'm using FactoryGirl and I have functional tests using factories, but I'm unsure of how to incorporate so many parts in a test. 我正在使用FactoryGirl,并且使用工厂进行了功能测试,但是我不确定如何在测试中包含这么多部分。

You can use Rack Test. 您可以使用机架测试。

https://github.com/rack-test/rack-test https://github.com/rack-test/rack-test

Below is an example. 下面是一个例子。 First we'll create a user and an associated stock_list. 首先,我们将创建一个用户和一个关联的stock_list。 You should have examples for doing this in your functional tests. 在功能测试中,应该有执行此操作的示例。 Then we need to find a way to pass the token that is needed. 然后,我们需要找到一种传递所需令牌的方法。 In rack-test, you can pass params. 在机架测试中,您可以传递参数。 You'll need to pass the key and value of a key that will work in your test environment. 您需要传递可以在您的测试环境中使用的密钥和密钥的值。 Then you can test that the controller action actually produces the results that you hope for. 然后,您可以测试控制器动作是否确实产生了希望的结果。 Here I'm supposing that we have count 0 of some model and that one gets created in the post action. 在这里,我假设某个模型的计数为0,并且在后期操作中创建了一个模型。

describe 'my_api' do
  let!( :user ){ create :user }
  let!( :stock_list ){ create :stock_list, user: user }

  specify do
    expect( SomeModel.count      ).to eq 0
    post "/stocklist/#{stock_list.id}/balance/show", { token: "some_token" }

    expect( SomeModel.count      ).to eq 1
    expect( last_response.status ).to eq 200
    expect( JSON.parse( last_response.body, symbloize_keys:true )[:my_value] ).to eq 'something'
  end
end

You can mock the controller method that returns the logged in user, like this: 您可以模拟返回登录用户的控制器方法,如下所示:

@user = FactoryGirl.create :user
# populate user with relationship objects

expect(controller).to_receive(:current_user).and_return(@user)

You can also set the http headers with authorization tokens if needed 您还可以根据需要使用授权令牌设置http标头

request.env['HTTP_AUTHORIZATION'] = token

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM