为api设计sign_in导致RSpec测试失败

时间:2014-02-07 13:49:43

标签: ruby-on-rails rspec devise

我正在使用Rails和Devise构建API。我的会话控制器继承自以下基本控制器

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 => 'example@gmail.com', :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方法?

2 个答案:

答案 0 :(得分:1)

使用以下内容添加spec/support/devise.rb文件:

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

另外,检查你的test.log,它实际上是使用json格式。我遇到了类似的问题,发现我必须在规范调用参数中强制format :json

答案 1 :(得分:1)

Andreamazz向我指出了test.logs,它显示我创建的用户已经确认(我正在使用Devise确认)。我用user.confirm!在之前(:每个),一切都在过去。

describe "DELETE destroy" do
  before(:each) do
    @user1 = User.create!(:email => 'example@gmail.com', :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

谢谢!

相关问题