Rails 3如何在规范之间重置控制器before_filters?

时间:2011-02-08 21:06:28

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

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

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

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

例如,在以下规范中,第二个'it'未通过:

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

2 个答案:

答案 0 :(得分:0)

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

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”上下文中的示例。

答案 1 :(得分:0)

我在子类而不是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