对于通配符路由,Rspec路由测试失败

时间:2014-06-12 08:27:06

标签: ruby-on-rails ruby-on-rails-4 rspec routing rspec-rails

规格/路由/ user_spec.rb

require 'rails_helper'
require 'spec_helper'

describe User do
    it 'should route properly' do
        expect(get: '/users').to route_to(controller: 'users', action: 'index')
        expect(get: '/foo/bar').to route_to(controller: 'users', action: 'index')

    end
end

配置/ routes.rb中

resources :users

match '*path', to: "users#index", via: :get

当我使用浏览器点击此网址时,此部分可以正常运行。

登录

Started GET "/foo/bar" for 127.0.0.1 at 2014-06-12 13:42:39 +0530
Processing by UsersController#index as HTML
  Parameters: {"path"=>"foo/bar"}
  User Load (34.6ms)  SELECT "users".* FROM "users"
  Rendered users/index.html.erb within layouts/application (51.1ms)
Completed 200 OK in 261ms (Views: 222.4ms | ActiveRecord: 36.8ms)

但是当我使用:

运行我的测试时
rspec spec/routing/user_spec.rb

它因以下错误

而失败
Failure/Error: expect(get: '/foo/bar').to route_to(controller: 'users', action: 'index')
       The recognized options <{"controller"=>"users", "action"=>"index", "path"=>"foo/bar"}> did not match <{"controller"=>"users", "action"=>"index"}>, difference:.
       --- expected
       +++ actual
       @@ -1 +1 @@
       -{"controller"=>"users", "action"=>"index"}
       +{"controller"=>"users", "action"=>"index", "path"=>"foo/bar"}
     # ./spec/routing/user_spec.rb:7:in `block (2 levels) in <top (required)>'

我做错了什么,如何纠正这个以使测试通过?

1 个答案:

答案 0 :(得分:1)

Rails将与通配符段('foo/bar')匹配的路径部分(*path)分配给与段名称相同的请求参数,因此操作可以看到客户端如何获取那里。

您只需将参数添加到测试所需的结果中:

describe UserController do
  describe 'wildcard route'
    it "routes to users#index with path set to the requested path" do
      expect(get: '/foo/bar').to route_to(
        controller: 'users', action: 'index', path: 'foo/bar')
    end
  end
end