【问题标题】:How to mock request object for rspec helper tests?如何模拟 rspec 助手测试的请求对象?
【发布时间】:2010-10-27 03:59:24
【问题描述】:

我有一个视图助手方法,它通过查看 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 运行它时,我得到了这个:

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

谁能帮我弄清楚我应该怎么做才能解决这个问题? 我如何模拟此示例的“请求”对象?

有没有更好的方法来生成使用子域的 url?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec rspec2 view-helpers


    【解决方案1】:

    你必须在 helper 方法前面加上 '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】:

    这不是您问题的完整答案,但为了记录,您可以使用 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
    

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题,我发现这个解决方案可行:

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

      【讨论】:

      • 对我来说,在控制器中它与controller.request.host = "http://test_my.com/"一起工作
      【解决方案4】:

      这对我有用:

      expect_any_instance_of(ActionDispatch::Request).to receive(:domain).exactly(1).times.and_return('domain')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-17
        • 2012-09-14
        相关资源
        最近更新 更多