簡體   English   中英

在Rails 4中使用rSpec在api測試用例中出錯

[英]Got error in api test case using rSpec in Rails 4

我正在開發使用Rails 4應用程序。 我只是開始編寫測試用例,但是使用rSpec and capybara在登錄API測試用例中遇到了問題。

下面是API控制器文件

---------------------- app/controllers/api/users_controller.rb --------------

class Api::UsersController < Api::ApiController
  before_action :set_user_api, except: [:login] 

  api :GET, '/api/users/login', "Get user token using credentials"
  param :email, String, "User email", :required => true
  param :password, String, "User password", :required => true
  def login
    @user= User.find_by_email(params[:email])
    if @user != nil && @user.authenticate(params[:password])
      if @user.token == nil
        @user.generate_token
        @user.save!
      end
      render action: 'withKey'
    else
      error(401, 401, "Could not authenticate user")
    end
  end
end

使用POSTMAN中的get方法成功運行

我在下面的測試案例中對此進行了編碼:

------------------------ spec/helpers/api/users_helper_spce.rb ----------------

require 'spec_helper'

RSpec.describe Api::UsersHelper, :type => :request do

    describe "Test Login Api" do
       it "Login Api" do
        params = {
                :email => "two@gmail.com",
                :password => "12345678"
        }

        get "/api/users/login", params
        # puts response.inspect
        expect(response.status).to eq(200)
       end
    end
end

我在下面出現錯誤:

  1) Api::UsersHelper Test Login Api Login Api
     Failure/Error: expect(response.status).to eq(200)

       expected: 200
            got: 401

       (compared using ==)
     # ./spec/helpers/api/users_helper_spec.rb:24:in `block (3 levels) in <top (required)>'

我在用於登錄網站及其成功的api中使用的憑據。

怎么了..我找不到。

任何一個經驗。

您需要在創建用戶之前對其進行簽名。 如果您使用FactoryGirls寶石,它將是這樣的

let(:user) {Factory(:user, email: "two@gmail.com", password: "12345678")}
describe "Test Login Api" do
  before { user }
  it "Login Api" do
    ...
RSpec.describe Api::UsersHelper, :type => :request do   
    describe "Test Login Api" do
           it "Login Api" do
            params = {
                       :email => "abc@gmail.com",
                       :password => "12345678"
               }

               create_user("abc", "xyz", params[:email], params[:password])
               get "/api/users/login", params
               expect(response.status).to eq(200)
           end
    end
end

我添加了一種方法,該方法首先注冊用戶,因為測試用例每次都要使用測試數據庫,並且每次使用空白。 所以我找不到用戶數據,這就是為什么需要先創建用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM