Bud*_*hiP 22 rspec ruby-on-rails view-helpers rspec2 ruby-on-rails-3
我有一个视图助手方法,它通过查看request.domain和request.port_string来生成一个url.
   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运行时,我得到了这个:
Run Code Online (Sandbox Code Playgroud)Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx" `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`
任何人都可以帮我弄清楚我该怎么做才能解决这个问题?如何模拟此示例的"请求"对象?
有没有更好的方法来生成使用子域的URL?
提前致谢.
Net*_*rat 22
你必须在'helper'前面加上辅助方法:
describe ApplicationHelper do
  it "should prepend subdomain to host" do
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end
除了测试不同请求选项的行为外,您还可以通过控制器访问请求对象:
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
seb*_*seb 11
这不是您的问题的完整答案,但对于记录,您可以使用模拟请求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
我遇到了类似的问题,我发现这个解决方案有效:
before(:each) do
  helper.request.host = "yourhostandorport"
end
| 归档时间: | 
 | 
| 查看次数: | 21781 次 | 
| 最近记录: |