2016-11-29 11 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

expect文のすぐ上に、これらの3行を入れます: 'p response、p response.status、p response.body'。それぞれの出力は何ですか?また、個人的には、これらのRSpecヘルパーがテストエラーをあいまいにすることがあります。私はそのテストを 'expect(response.status).to eq(200)'と書き直したいと思います。その後、あなたはその状態が本当に何だったのかを見るでしょう。 – steel

+0

@steelこれは、 'p response.status'でNoMethodError' undefined method 'status 'for nil:NilClass'を返します。私はこれらの行をコメントして、あなたの提案 'expect(response.status).to eq(200)'(チップのおかげで、btw)を試しました。 – 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を使用する必要がある)ことが知られている必要があります理由はわかりません。

関連する問題