Rspec请求规范的空响应

时间:2016-11-29 23:02:46

标签: ruby-on-rails ruby rspec

我正在尝试为我的第一个Rails应用编写请求规范,但响应对象是nil。 Rspec对我来说仍然是黑魔法,所以我可能会遗漏一些非常基本的东西,但是给出了here示例,我认为这样可行。当我运行Rails服务器时,我可以通过cURL进行身份验证,我的控制器规范工作正常。

这是我的要求规范:

# spec/requests/tokens_request_spec.rb
require 'rails_helper'

RSpec.describe Api::V1::TokensController, type: :request do
  context "getting the token" do
    let(:user) { create(:user) }

    it 'status code is 2xx' do
      post "/api/v1/login", { auth: { email: user.email, password: user.password } }, { accept: "application/json" }
      expect(response).to have_http_status(:success)
    end
  end
end

这是我的控制器:

# app/controllers/api/v1/tokens_controller.rb
class Api::V1::TokensController < ApplicationController
  def create
    user = User.find_by(email: user_params["email"])
    return render json: { jwt: Auth.issue(user: user.id) } if user.authenticate(user_params["password"])
    render json: { message: "Invalid credentials" }, status: 401
  end

  private

  def user_params
    params.require(:auth).permit(:email, :password)
  end
end

这是我的测试输出:

Failures:

  1) Api::V1::TokensController getting the token status code is 2xx
     Failure/Error: expect(response).to have_http_status(:success)
       expected the response to have a success status code (2xx) but it was
     # ./spec/requests/tokens_request_spec.rb:13:in `block (3 levels) in <top (required)>'
     # ./spec/spec_helper.rb:27:in `block (3 levels) in <top (required)>'
     # ./spec/spec_helper.rb:26:in `block (2 levels) in <top (required)>'

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

好的,我有这个工作。

it 'status code is 200' do
   post "/api/v1/login", { auth: { email: user.email, password: user.password } }, { accept: "application/json" }
      expect(last_response.status).to eq(200)
end

我不确定为什么我需要使用last_response或我应该如何知道(特别是因为官方文档告诉我应该使用response),但确实如此。