【发布时间】:2014-02-07 13:49:42
【问题描述】:
我正在使用 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
这在通过 curl 测试 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 方法?
【问题讨论】:
标签: ruby-on-rails rspec devise