2011-02-08 56 views
0

我正在写一个插件的规格,有不同的模块,用户可以选择加载。 其中一些模块动态地将before_filters添加到ApplicationController。Rails 3如何在规范之间重置控制器before_filters?

问题是,如果模块X的规格运行并添加了before_filter,则稍后运行的模块Y的规格将失败。我需要以某种方式运行清洁 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 

回答

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

+0

感谢,但它并不在我的情况下工作。我已经为我的问题添加了一个示例规范。 – 2011-02-09 21:36:41

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 
相关问题