【问题标题】:How should I test routes and controllers with rspec?我应该如何使用 rspec 测试路由和控制器?
【发布时间】:2013-11-25 15:50:07
【问题描述】:

我只有一个规范,位于 spec/controllers/statuses_spec.rb

这是它的内容:

require 'spec_helper'

describe StatusesController do
    describe "routing" do

    it "routes to #index" do
        get("/statuses").should route_to("statuses#index")
    end

  end
end

我只想说,我有一个简单的状态脚手架,状态控制器具有 CRUD 的标准操作,包括索引操作。

但是,在运行上述测试时出现此错误:

15:39:52 - INFO - Running: ./spec/controllers/statuses_spec.rb:6
Run options: include {:locations=>{"./spec/controllers/statuses_spec.rb"=>[6]}}
F

Failures:

  1) StatusesController routing routes to #index
     Failure/Error: get("/statuses").should route_to("statuses#index")
     ActionController::UrlGenerationError:
       No route matches {:controller=>"statuses", :action=>"/statuses"}
     # ./spec/controllers/statuses_spec.rb:8:in `block (3 levels) in <top (required)>'

Finished in 0.21772 seconds
1 example, 1 failure

Rspec 假设我正在处理statuses 控制器,我猜这有点直观,因为我在规范的描述块中引用了它,并且它认为我已经传递给 get 方法的字符串 ( '/statuses') 是函数。

坦率地说,我真的不喜欢这个。我希望能够测试 URL 栏中的确切字符串是否指向正确的 controller#action 对。无论如何,我按照 rspec 所说的那样做:

require 'spec_helper'

describe StatusesController do
    describe "routing" do

    it "routes to #index" do
        get("index").should route_to("statuses#index")
    end

  end
end

但是,现在我明白了:

Run options: include {:locations=>{"./spec/controllers/statuses_spec.rb"=>[6]}}
F

Failures:

  1) StatusesController routing routes to #index
     Failure/Error: get("index").should route_to("statuses#index")
     NoMethodError:
       undefined method `values' for #<ActionController::TestResponse:0x00000102bd3208>
     # ./spec/controllers/statuses_spec.rb:8:in `block (3 levels) in <top (required)>'

Finished in 0.31019 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/statuses_spec.rb:6 # StatusesController routing routes to #index

我收到关于 values 方法的无方法错误。价值观?说真的,只是什么?我不知道为什么会收到此错误。这是我的规范助手:

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
  # ## Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    Capybara.run_server = true
    Capybara.javascript_driver = :webkit
    Capybara.default_selector = :css
    Capybara.server_port = 7171
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.include RSpec::Rails::RequestExampleGroup, type: :feature

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"
end

【问题讨论】:

  • 路由规格不属于 /controllers 文件夹
  • 是的 -1 尽管是这个主题的新手,但这可能会对其他人有所帮助,并且该领域的文档非常不完整(apneadiving 的链接是第三方的)。一定会喜欢这个网站!
  • 是的,-1 很苛刻,只是做了+1,但提醒阅读:)

标签: ruby-on-rails rspec capybara


【解决方案1】:

测试路由,尤其是标准 RESTful 路由,不是标准做法。

a) 您不想浪费精力重新测试 Rails 的路由功能

b) 当您的控制器或 request 规范无法路由请求时,它们应该会失败

通常情况下,编写和维护路由测试并不能带来太多价值和增强信心。 当路线变得复杂且容易出错时,请考虑对其进行测试。

也就是说,RSpec 提供了一个route_to matcher 用于指定请求是可路由的。

路由规范的推荐位置在spec/routing 下,尽管在控制器规范旁边看到路由规范并不少见。例如

describe VersionsController do
  describe 'routing' do
    it 'routes GET /version to VersionsController#show' do
      expect(get: '/version').to route_to(controller: 'versions', action: 'show')
    end
  end
end

shoulda-matchers gem 有自己的路由匹配器,允许您编写测试,例如

describe PostsController do
  it { should route(:get, '/posts').to(action: :index) }
  it { should route(:get, '/posts/1').to(action: :show, id: 1) }
end

【讨论】:

  • 谢谢。我认为通常不需要路由规范,但是当我们对约束对象和诸如此类的东西感到奇怪时,将它们用作单元测试是正确的。
【解决方案2】:

路由应该作为集成测试的一部分来完成。集成测试是您测试应用程序的重要工作流程的地方 - 更具体地说,是否定义了 URL 似乎是一个重要的工作流程。

您的集成测试看起来像任何普通的集成测试:

require 'test_helper'
class RoutesTest < ActionController::IntegrationTest
   test "route test" do
       assert_generates "/videos/5", { :controller => "videos", :action => "show", :id => "1" }
       assert_generates "/about", :controller => "pages", :action => "about"
   end
end

关于@jemminger 没有测试路线的回应 - 虽然是 Rail 的测试验证了 routes.rb 是否有效,但 Rail 没有责任测试您的路线中是否定义了 http://yoursite.com/users。需要注意的是,大多数路由测试都可以在现有的集成测试中完成,因此针对路由的特定测试可能是多余的。

我能想到的具体用例是所有已经或将要从 Rails 2 升级到 Rails 3 的人。定义路由的代码发生了很大变化,最好从测试中发现路由正确升级,而不是用户报告 404 错误时。

【讨论】:

    【解决方案3】:
    it { expect(put: "/posts/1").to route_to(controller: "posts", action: "update", id: "1") }
    
    it { expect(GET: "/posts/1").to route_to(controller: 'posts', action: 'show', id: "1") }
    
    if { expect(get: '/posts').to route_to(controller: 'posts', action: 'index') }
    

    如果没有要删除的路由

    it { expect(delete: "/posts/1").to_not be_routable }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多