1

Rails 新手在这里。

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

在我的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

路线.rb:

Tat::Application.routes.draw do

    root to: "index#page"

end

索引控制器:

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)>

'

我不明白?!

谢谢。

4

1 回答 1

3

欢迎来到 Rails 世界!测试有许多不同的风格。您似乎将控制器测试与路由测试混淆了。

您看到此错误是因为root_path正在返回/. RSpecget :action控制器内的测试旨在调用该控制器上的该方法。

如果你注意到你的错误信息,它会说:action => '/'

要测试您的控制器,请将您的测试更改为:

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"
  )
于 2013-04-22T23:55:20.690 回答