Ruby-on-rails 如何模拟 rspec 帮助程序测试的请求对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4029861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock request object for rspec helper tests?
提问by BuddhiP
I've a view helper method which generates a url by looking at request.domain and request.port_string.
我有一个视图助手方法,它通过查看 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
I would like to test this method using rspec.
我想使用 rspec 测试这个方法。
describe ApplicationHelper do
it "should prepend subdomain to host" do
root_with_subdomain("test").should = "test.xxxx:xxxx"
end
end
But when I run this with rspec, I get this:
但是当我用 rspec 运行它时,我得到了这个:
Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx" `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`
Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx" `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`
Can anyone please help me figure out what should I do to fix this? How can I mock the 'request' object for this example?
谁能帮我弄清楚我应该怎么做才能解决这个问题?如何模拟此示例的“请求”对象?
Are there any better ways to generate urls where subdomains are used?
有没有更好的方法来生成使用子域的 url?
Thanks in advance.
提前致谢。
采纳答案by Netzpirat
You have to prepend the helper method with 'helper':
您必须在辅助方法前加上“helper”:
describe ApplicationHelper do
it "should prepend subdomain to host" do
helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
end
end
Additionally to test behavior for different request options, you can access the request object throught the controller:
除了测试不同请求选项的行为之外,您还可以通过控制器访问请求对象:
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
回答by seb
This isn't a complete answer to your question, but for the record, you can mock a request using ActionController::TestRequest.new(). Something like:
这不是您问题的完整答案,但为了记录,您可以使用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
回答by 23inhouse
I had a similar problem, i found this solution to work:
我有一个类似的问题,我发现这个解决方案有效:
before(:each) do
helper.request.host = "yourhostandorport"
end
回答by hlcs
This worked for me:
这对我有用:
expect_any_instance_of(ActionDispatch::Request).to receive(:domain).exactly(1).times.and_return('domain')

