首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用RSpec存根ApplicationController方法

使用RSpec存根ApplicationController方法
EN

Stack Overflow用户
提问于 2011-09-11 07:22:44
回答 2查看 1.7K关注 0票数 0

我正在尝试在rspec中设置控制器的存根身份验证。当我存根authorize方法时,无论我提供什么值,测试都会通过。

控制器:

代码语言:javascript
复制
class FoosController < ApplicationController
  before_filter :authorize
  ...
end

ApplicationController:

代码语言:javascript
复制
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user

  protected

  def authorize
    return true if current_user

    flash[:error] = 'Please login'
    redirect_to signin_path
    false
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

规格:

代码语言:javascript
复制
# this passes (expected)
it "..." do
  controller.stubs(:current_user).returns(User.new)
  get :index
  response.should be_success
end

# this fails (expected)
it "..." do
  controller.stubs(:current_user).returns(nil)
  get :index
  response.should be_success
end

# this passes (expected)
it "..." do
  controller.stubs(:authorize).returns(true)
  get :index
  response.should be_success
end

# Problem: this passes (unexpected)
it "..." do
  controller.stubs(:authorize).returns(false)
  get :index
  response.should be_success
end

似乎只要我使用stub :authorize,无论设置什么值,它都会传递before_filter。我认为这可能是受保护的/helper_method名称,但使用这些名称并没有改变任何事情。

为什么存根:authorize with false会导致before_filter通过?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-11 09:02:04

我认为您需要检查正在呈现的内容。

看看你的代码,如果当authorize返回false时调用链确实停止了,那么会发生什么呢?

没有重定向或渲染调用。

所以这将是一个空洞的回应?

空的回答仍然是200分。

但是,根据您使用的Rails版本,在Rails3.1中,返回falsebefore_filter不再停止链是可能的。

实际上,想要停止链的before_filter应该执行以下操作之一

  1. redirect somewhere
  2. render something
  3. raise something
票数 2
EN

Stack Overflow用户

发布于 2013-07-15 05:25:17

我会回答你的最后一个问题Why does stubbing :authorize with false cause the before_filter to pass?

您使用的是存根方法authorize,它会停止调用其中的所有代码,但会返回与存根一起显式返回的内容。

它工作正常,因为当您将current_user存根到false时,authorize将被完全调用。我认为你的最后测试实际上并没有为你测试任何东西,但这只是我的观点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7375333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档