RSpec路由失败



Rails newb here.

尝试RSpec测试索引路由的状态码为200。

我在<<p> strong> index_controller_spec.rb :
require 'spec_helper'
describe IndexController do
    it "should return a 200 status code" do
    get root_path
    response.status.should be(200)
  end
end

routes.rb:

Tat::Application.routes.draw do
    root to: "index#page"
end

index_controller:

class IndexController < ApplicationController
    def page
    end
end

当我访问浏览器时一切正常,但RSpec命令行给一个错误:

IndexController should return a 200 status code
     Failure/Error: get '/'
     ActionController::RoutingError:
       No route matches {:controller=>"index", :action=>"/"}
     # ./spec/controllers/index_controller_spec.rb:6:in `block (2 levels) in <top (required)>

我不明白?

谢谢。

欢迎来到Rails世界!测试有很多不同的方式。看来你把控制器测试和路由测试搞混了。

你看到这个错误是因为root_path返回/。RSpec控制器测试中的get :action意味着在该控制器上调用该方法。

如果您注意到您的错误消息,它说:action => '/'

要测试控制器,将test更改为:

require 'spec_helper'
describe IndexController do
  it "should return a 200 status code" do
    get :page
    response.status.should be(200)
  end
end

如果您对路由测试感兴趣,请参阅https://www.relishapp.com/rspec/rspec-rails/docs/routing-specs。示例如下:

{ :get => "/" }.
  should route_to(
    :controller => "index",
    :action => "page"
  )

最新更新