加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rp中的RSpec:如何跳过before_filter?

发布时间:2020-12-16 20:29:03 所属栏目:百科 来源:网络整理
导读:我试图测试我的控制器,并保持关注的分离. 第一个问题是“谁能够执行哪些行动?” 我正在使用authlogic进行身份验证,并使用be9’s acl9进行授权.但这并不重要,我所有的授权问题都是在before_filter中处理的.我正在测试这样一个before_filter类似的东西: desc
我试图测试我的控制器,并保持关注的分离.

第一个问题是“谁能够执行哪些行动?”
我正在使用authlogic进行身份验证,并使用be9’s acl9进行授权.但这并不重要,我所有的授权问题都是在before_filter中处理的.我正在测试这样一个before_filter类似的东西:

describe SomeModelsController,"GET to index (authorization)" do
  before(:each) do
    @siteadmin = mock_model(User)
    @siteadmin.stub!(:has_role?).with("siteadmin",nil).and_return(true)
  end

  it "should grant access to a siteadmin" do
    controller.should_receive(:current_user).at_least(:once).and_return(@siteadmin)
    get :index
    response.should be_success
  end
end

这个规格工作很好!

现在,第二个问题是“行动是否应该做什么?”
这不涉及检查授权.最好的/最干净的解决方案是将before_filter全部跳过,只需要执行以下操作:

describe SomeModelsController,"GET to index (functional)" do
  it "should find all Models" do
    Model.should_receive(:find).with(:all)
  end
end

无需担心哪个角色必须先登录的用户.现在我解决了:

describe SomeModelsController,"GET to index (functional)" do
  before(:each) do
    @siteadmin = mock_model(User)
    @siteadmin.stub!(:has_role?).with("siteadmin",nil).and_return(true)
    controller.stub!(:current_user).and_return(@siteadmin)
   end

  it "should find all Models" do
    Model.should_receive(:find).with(:all)
  end
end

如果我现在决定我的siteadmin不再有权访问索引操作,那么它不仅会破坏一个规范 – 即在这种情况下破坏的规范,而且也是完全无关的第二个规范.

我知道这基本上是一个小问题,但如果有人可以提出(优雅)的解决方案,那将是很好的!

解决方法

要跳过之前的过滤器:
controller.class.skip_before_filter :name_of_method_used_as_before_filter

一个注意事项(mentioned the docs)是这样,它只适用于方法引用过滤器,而不是过程.

或者,您可以存根current_user.has_role?

describe SomeModelsController,"GET to index (functional)" do
  before(:each) do
    controller.current_user.stub!(:has_role?).and_return(true)
  end

  it "should find all Models" do
    Model.should_receive(:find).with(:all)
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读