如何为RSpec helper测试模拟请求对象?

27

我有一个视图助手方法,它通过查看请求的域名和端口字符串来生成一个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运行这个代码时,出现了以下问题:

 Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx"
 `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`
可以有人帮我弄清楚应该怎么做来修复这个问题吗? 如何为这个例子模拟'request'对象?是否有更好的方法生成使用子域的URL?谢谢。
4个回答

24

你需要在帮助方法前加上 '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

2
它报错了:遇到异常:#<NameError: undefined local variable or method `controller'。我的代码看起来像是 controller.request.host = 'lvh.me:3001' expect (helper.request.subdomain).to eq('merchant') - shailesh

14

这不是对你问题的完整回答,但是值得记录的是,你可以使用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

9

我有一个类似的问题,我找到了这个解决方案:

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

对于我来说,在控制器中使用 controller.request.host = "http://test_my.com/" 是可以工作的。 - AnkitG

0
这对我有用:
expect_any_instance_of(ActionDispatch::Request).to receive(:domain).exactly(1).times.and_return('domain')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接