【问题标题】:Test controller method that uses request-url with Rspec使用带有 Rspec 的 request-url 的测试控制器方法
【发布时间】:2014-01-04 08:42:36
【问题描述】:

我为 Rails 编写了一个 gem,它用某种方法扩展了 ApplicationController。此方法解析当前 URL 并使用结果进行查找。它看起来像这样(简化):

@current_account = Account.where(subdomain => request.subdomains.first).first

我想在 gem 中包含一个测试,断言根据给定的 URL 正确查找了子域。

我在编写测试时遇到了两个问题:

1) 由于我在 gem 中进行测试,因此没有控制器(或 Rails 应用程序),所以我实际上不知道从哪里开始(单元测试,控制器测试?)

2) 我到处搜索,但找不到在 Rspec 中设置 request 哈希以进行测试的方法。我希望我能够做类似request.url = 'account1.example.com' 的事情

非常感谢有关如何在 Rspec 上针对这种情况设置适当测试的任何帮助

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec


    【解决方案1】:

    如果你在做一个控制器测试,那么 URLs 通常在配置中指定,比如:

    config.action_controller.default_url_options = { host: 'www.test.host' }
    

    也就是说,如果您将其作为 Rails 应用程序进行测试。

    要测试抽象类中的方法是否有效,最好的选择是创建一个测试子类,并使用它进行测试。类似的东西

    class TestController < ApplicationController; end
    

    然后围绕这个控制器做你的规范,它应该完全像ApplicationController

    编辑

    这将是我提议的一个例子:

    class TestController < ApplicationController
      def index
        render text: 'fake page' #This is so the action does not fail
      end
    
    end
    
    describe TestController do
      it 'searches for the current account in the right subdomain' do
        Account.should_receive(:where).with({subdomain: 'www'})
    
        get :index
      end
    end
    

    【讨论】:

    • 这听起来很明智,尽管我仍然不清楚测试会是什么样子。你能给我看一个使用你的方法的测试例子吗?
    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多