2016-11-29 76 views
1

我想写我的第一个Rails应用程序的请求规范,但响应对象是nil。 Rspec对我来说仍然是黑暗的魔法,所以我可能会错过一些非常基本的东西,但以here为例,我认为这是行得通的。当我运行Rails服务器时,我可以通过cURL进行身份验证,并且我的控制器规范工作正常。Rspec请求规范的空回复

这里是我的要求规格:

# 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)>' 

任何帮助是极大的赞赏。

+0

就在你的期望声明之上,放上这3行:'p response,p response.status,p response.body'。每个输出是什么?另外,我个人发现这些RSpec帮助器可以掩盖测试错误。我会重写那个测试为'expect(response.status).to eq(200)'。然后你会看到真实的状态。 – steel

+0

@steel它给了我一个NoMethodError'未定义的方法'状态'nil:NilClass'在'p response.status'。我评论了这些内容并尝试了你的建议,expect(response.status).to eq(200)'(感谢提示,顺便说一句),这给了我同样的错误。 – HyperMeat

+0

尝试在控制器的'create'方法上添加这个。 'respond_to:json' – steel

回答

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),但它是。

相关问题