2013-10-02 54 views
3

我試圖編寫一個規範來測試我的user_login API,但在運行規範時不斷收到JSON電子郵件/密碼錯誤401。我正在做以下事情:如何編寫一個請求規範來測試用戶登錄?

require 'spec_helper' 

describe User do 
    subject(:user) do 
    Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1') 
    User.create!(email: '[email protected]', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female') 
    end 

    it "is logged in" do 
    post "/api/v1/login", user_login: {email: '[email protected]', password: '12345678' } 
    response.status.should be(201) 
    end 
end 

任何想法?

EDIT 1

這是我的sessions_controller,當用戶經由API記錄在其中被使用。

class Api::V1::SessionsController < Devise::SessionsController 
    before_filter :authenticate_user!, except: [:create, :destroy] 
    before_filter :ensure_params_exist 
    skip_before_filter :verify_authenticity_token 

    def create 
    resource = User.find_for_database_authentication(email: params[:user_login][:email]) 
    return invalid_login_attempt unless resource 

    if resource.valid_password?(params[:user_login][:password]) 
     sign_in("user", resource) 
     resource.ensure_authentication_token! 
     render 'api/v1/sessions/new.json.jbuilder', status: 201 
     return 
    end 
    invalid_login_attempt 
    end 

    def destroy 
     current_user.reset_authentication_token 
     render json: {success: true} 
    end 

    protected 

    def ensure_params_exist 
    return unless params[:user_login].blank? 
    render json: {success: false, message: "missing user_login parameter"}, status: 422 
    end 

    def invalid_login_attempt 
    render 'api/v1/sessions/invalid.json.jbuilder', status: 401 
    end 
end 
+0

這將有助於如果您發佈您的登錄控制器 – usha

+0

我剛剛添加它。謝謝! – Arel

+0

@phoet,什麼? – Arel

回答

1

我非常接近,也許這就是爲什麼我有這麼多麻煩。以下是我落得這樣做:

require 'spec_helper' 

describe "sessions" do 
    before do 
    FactoryGirl.create(:program) 
    @user = FactoryGirl.create(:user) 
    end 

    describe "user" do 
    it "is logged in" do 
    post "/api/v1/login", user_login: {email: @user.email, password: @user.password } 

     response.status.should be(201) 
    end 
    end 
end 

我切換了subject塊的before塊,並用實例變量的電子郵件和密碼。而已!

相關問題