代码之家  ›  专栏  ›  技术社区  ›  erik

如何在Rails中截取或模拟request.subdomains方法?

  •  3
  • erik  · 技术社区  · 15 年前

    我正在尝试在我的Rails应用程序中编写一些功能测试,在应用程序_Controller.rb中,我有:

    before_filter :current_account
    def current_account
      @current_account ||= Account.find_by_subdomain!(request.subdomians.first)
    end
    

    运行测试时, request.subdomains 不包含我要查找的有效子域,因此无法运行任何功能测试。

    有没有可能把 current_account 方法或模拟 请求.子域 对象?

    3 回复  |  直到 13 年前
        1
  •  5
  •   Shadwell    15 年前

    在您的功能测试中,您应该能够做到(使用Mocha):

    @request.expects(:subdomains).returns(['www'])
    
        2
  •  1
  •   Pietro Di Bello    15 年前

    对于我(和Rails 2.3.4),正确的声明是

    @controller.request.expects(:subdomains).returns(['www'])
    

    因为我不能直接访问@request。

        3
  •  1
  •   shingara    13 年前
    @controller.instance_variable_set(:@request, OpenStruct.new({:subdomains => 'www'}))
    

    您可以访问Ruby中的任何内容:)