2010-10-27 101 views
19

我有一個視圖助手方法,它通過查看request.domain和request.port_string來生成一個url。如何模擬RSpec幫助程序測試的請求對象?

module ApplicationHelper 
     def root_with_subdomain(subdomain) 
      subdomain += "." unless subdomain.empty?  
      [subdomain, request.domain, request.port_string].join 
     end 
    end 

我想用rspec來測試這個方法。

describe ApplicationHelper do 
    it "should prepend subdomain to host" do 
    root_with_subdomain("test").should = "test.xxxx:xxxx" 
    end 
end 

但是當我運行這個使用RSpec,我得到這個:

Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx" 
`undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>` 

任何人都可以請幫我找出我應該怎麼做才能解決這個問題? 我該如何嘲笑這個例子中的'request'對象?

有沒有更好的方法來生成使用子域名的網址?

在此先感謝。

回答

21

你有「幫手」前面加上輔助方法:

describe ApplicationHelper do 
    it "should prepend subdomain to host" do 
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx" 
    end 
end 

此外,以測試行爲的不同要求選擇,您可以訪問請求對象throught控制器:

describe ApplicationHelper do 
    it "should prepend subdomain to host" do 
    controller.request.host = 'www.domain.com' 
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx" 
    end 
end 
+2

它給錯誤:遇到異常:# shailesh 2013-04-23 04:34:37

7

我有類似的問題,我發現這個解決方案的工作:

before(:each) do 
    helper.request.host = "yourhostandorport" 
end 
+0

對我來說,在控制它'控制器工作。 request.host =「http://test_my.com/」 – AnkitG 2013-08-15 10:50:35

9

這不是一個完整回答你的問題,但爲了記錄,你可以使用ActionController::TestRequest.new()嘲笑一個請求。例如:

describe ApplicationHelper do 
    it "should prepend subdomain to host" do 
    test_domain = 'xxxx:xxxx' 
    controller.request = ActionController::TestRequest.new(:host => test_domain) 
    helper.root_with_subdomain("test").should = "test.#{test_domain}" 
    end 
end 
+0

你能否詳細說明一下? – 2012-06-12 22:52:44