2013-01-13 83 views
4

我試圖通過爲常用測試添加一些控制器宏來幹掉我的RSpec示例。在這個有些簡單的例子,我創建了一個簡單的測試是否得到頁面結果直接到另一個頁面宏:將命名路由傳遞給RSpec中的控制器宏

def it_should_redirect(method, path) 
    it "#{method} should redirect to #{path}" do 
    get method 
    response.should redirect_to(path) 
    end 
end 

我試圖把它像這樣:

context "new user" do 
    it_should_redirect 'cancel', account_path 
end 

當運行測試,我得到一個錯誤,指出它不承認account_path:

未定義的局部變量或方法`account_path」爲...(NameError)

我試過按照this SO thread on named routes in RSpec給出的指導包括Rails.application.routes.url_helpers,但仍然收到相同的錯誤。

如何將命名路由作爲參數傳遞給控制器​​宏?

回答

3

config.include Rails.application.routes.url_helpers附帶的網址幫助程序僅在示例中有效(以itspecify設置的程序段)。在示例組(上下文或描述)中,您不能使用它。嘗試使用符號和send而是像

# macro should be defined as class method, use def self.method instead of def method 
def self.it_should_redirect(method, path) 
    it "#{method} should redirect to #{path}" do 
    get method 
    response.should redirect_to(send(path)) 
    end 
end 

context "new user" do 
    it_should_redirect 'cancel', :account_path 
end 

不要忘了包括url_helpers來配置。

或致電例子裏面的宏:

def should_redirect(method, path) 
    get method 
    response.should redirect_to(path) 
end 

it { should_redirect 'cancel', account_path } 
+0

完美 - 謝謝! –

相關問題