2010-10-27 97 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