2011-02-08 54 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 
相關問題