【问题标题】:Rspec request spec's empty responseRspec 请求规范的空响应
【发布时间】:2017-04-14 03:04:31
【问题描述】:

我正在尝试为我的第一个 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)>'

非常感谢任何帮助。

【问题讨论】:

  • 在您的期望语句上方,放置以下 3 行:p response, p response.status, p response.body。每个的输出是什么?另外,就我个人而言,我发现这些 RSpec 助手可以掩盖测试错误。我将该测试重写为expect(response.status).to eq(200)。然后你会看到真正的状态是什么。
  • @steel 它给了我一个 NoMethodError undefined method status' for nil:NilClass` 在p response.status。我评论了这些行并尝试了你的建议,expect(response.status).to eq(200)(谢谢你的提示,顺便说一句),这给了我同样的错误。
  • 尝试在控制器中的 create 方法上方添加它。 respond_to :json
  • 我之前尝试过,但是当你创建一个带有 api 标志的 Rails 应用程序时,respond_to 没有定义。我遵循了this answer 的建议,但我仍然收到 response_to 的 NoMethodError。
  • 你可以尝试将post "/api/v1/login", { auth: { email: user.email, password: user.password } }, { accept: "application/json" } 放在before 块中

标签: ruby-on-rails ruby rspec


【解决方案1】:

好的,我已经搞定了。

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),但确实如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多