2014-02-07 26 views
1

我正在使用Rails和Devise构建API。我的会话控制器从下面为api设计sign_in导致RSpec测试失败

api/base_controller.rb 

module Api 
    class BaseController < ApplicationController 
    skip_before_filter :verify_authenticity_token 
    before_filter :authenticate_user_from_token! 
    respond_to :json 

    private 

    def authenticate_user_from_token! 
     user_token = params[:auth_token].presence 
     user  = user_token && User.find_by_authentication_token(user_token) 

     if user 
      sign_in user, store: false 
     else 
      render :json => {:success => false, :message => "Error with your credentials",  :status => 401} 
     end 
    end 
    end 
end 

我的会话控制器的破坏行动以下基本控制器继承:

api/sessions_controller.rb 

before_filter :authenticate_user_from_token!, :except => [:create] 


def destroy 
    current_user.reset_authentication_token 
    render :json => { 
    :success => true, 
    :status => 200 
    } 
end 

通过卷曲测试API时,这完美的作品。但是,我无法让我的Rspec测试通过销毁行为。来自Rspec的sign_in用户调用失败,所以响应是重定向。我没有尝试存根sign_in方法的任何成功。

Rspec的测试:

describe "DELETE destroy" do 
    before(:each) do 
    @user1 = User.create!(:email => '[email protected]', :password => 'helloworld', :password_confirmation => 'helloworld') 
    end 

    it "should render success json" do 
    delete :destroy, :auth_token => @user1.authentication_token 
    json = JSON.parse(response.body) 
    json.should include('success' => true, 'status' => 200) 
    end 

    ###this fails because the response is a redirect to the sign_in page 
end 

我应该如何去嘲讽从基本控制器内称为sign_in方法?

回答

1

添加spec/support/devise.rb文件与此内容:

RSpec.configure do |config| 
    config.include Devise::TestHelpers, :type => :controller 
end 

另外,请检查您的test.log中羯羊它的实际使用JSON格式。我有类似的问题,并发现我不得不在我的规格调用参数中强制format :json

+0

我已经包含在我的spec_helper.rb文件中。我可以在Rspec测试中使用sign_in(@user),但基本控制器内的sign_in调用仍然导致重定向到sign_in路径。 – user1280971

+0

你可以检查你的test.log是否它实际上使用json格式?我有一个类似的问题,并发现我不得不在我的规格调用中强制使用'format:json'。 – andreamazz

+1

谢谢你指点我的测试日志!它正在请求HTML,但这似乎不成问题。 我意识到我使用的是设计可确认的,并且正在创建一个未经确认的用户,导致登录时重定向。我设置了@ user1.skip_confirmation!并通过了所有测试! – user1280971

1

Andreamazz指出我的test.logs显示我创建的用户已被确认(我正在使用Devise confirmmable)。我使用user.confirm!在之前(:每个),一切都在传递。

describe "DELETE destroy" do 
    before(:each) do 
    @user1 = User.create!(:email => '[email protected]', :password => 'helloworld', :password_confirmation => 'helloworld') 
    @user1.confirm! 
    end 

    it "should render success json" do 
    delete :destroy, :auth_token => @user1.authentication_token 
    json = JSON.parse(response.body) 
    json.should include('success' => true, 'status' => 200) 
    end 
end 

谢谢!