【问题标题】:How can I stub or mock the request.subdomains method in Rails?如何存根或模拟 Rails 中的 request.subdomains 方法?
【发布时间】:2010-11-03 12:57:31
【问题描述】:

我正在尝试在我的 rails 应用程序中编写一些功能测试,在 application_controller.rb 中我有这个:

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

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

是否可以存根 current_account 方法或模拟 request.subdomains 对象?

【问题讨论】:

    标签: ruby-on-rails mocking integration-testing stubbing


    【解决方案1】:
    @controller.instance_variable_set(:@request, OpenStruct.new({:subdomains => 'www'}))
    

    你可以在 ruby​​ 中访问任何东西 :)

    【讨论】:

      【解决方案2】:

      对我(以及 Rails 2.3.4)来说,正确的说法是

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

      因为我无法直接访问@request。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2021-02-09
          • 1970-01-01
          • 1970-01-01
          • 2013-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-10
          相关资源
          最近更新 更多