【问题标题】:Rails 3 how to reset controller before_filters between specs?Rails 3 如何在规格之间重置控制器 before_filters?
【发布时间】:2011-02-08 21:06:28
【问题描述】:

我正在为一个插件编写规范,该插件具有用户可以选择加载的不同模块。 其中一些模块会动态地将 before_filters 添加到 ApplicationController。

问题有时是,如果模块 X 的规范运行并添加了一个 before_filter,那么稍后运行的模块 Y 的规范将失败。我需要以某种方式在 clean ApplicationController 上运行第二个规范。

有没有办法在过滤器之前删除或在规范之间完全重新加载 ApplicationController?

例如在以下规范中,第二个“它”没有通过:

describe ApplicationController do
  context "with bf" do
    before(:all) do
      ApplicationController.class_eval do
        before_filter :bf

        def bf
          @text = "hi"
        end

        def index
          @text ||= ""
          @text += " world!"
          render :text => @text
        end
      end
    end

    it "should do" do
      get :index
      response.body.should == "hi world!"
    end
  end

  context "without bf" do
    it "should do" do
      get :index
      response.body.should == " world!"
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec before-filter


    【解决方案1】:

    您应该能够使用上下文块来分隔两组示例。

    describe Something do
      context "with module X" do
        before(:each) do
          use_before_fitler
        end
    
        it_does_something
        it_does_something_else
      end
    
      context "without module X" do
        it_does_this
        it_does_that
      end
    end
    

    before_filter 应该只影响“with module X”上下文中的示例。

    【讨论】:

    • 谢谢,但在我的情况下它不起作用。我在我的问题中添加了一个示例规范。
    【解决方案2】:

    我会在子类上使用单独的规范而不是 ApplicationController 本身:

    # spec_helper.rb
    def setup_index_action
      ApplicationController.class_eval do
        def index
          @text ||= ""
          @text += " world!"
          render :text => @text
        end
      end
    end
    
    def setup_before_filter
      ApplicationController.class_eval do
        before_filter :bf
    
        def bf
          @text = "hi"
        end
      end
    end
    
    # spec/controllers/foo_controller_spec.rb
    require 'spec_helper'
    
    describe FooController do
    
      context "with bf" do
        before(:all) do
          setup_index_action
          setup_before_filter
        end
    
        it "should do" do
          get :index
          response.body.should == "hi world!"
        end
      end
    end
    
    
    # spec/controllers/bar_controller_spec.rb
    require 'spec_helper'
    
    describe BarController do
      before(:all) do
        setup_index_action
      end
    
      context "without bf" do
        it "should do" do
          get :index
          response.body.should == " world!"
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2013-11-18
      • 2012-10-07
      • 2014-03-02
      相关资源
      最近更新 更多