rspec-rails:失败/错误:获取"/"没有路由匹配

MrB*_*MrB 6 rspec routes ruby-on-rails

尝试rspec-rails.我得到一个奇怪的错误 - 没有找到路由,即使我在运行rails s时可以在浏览器中正常访问它们.

我甚至尝试过/

Failure/Error: get "/"
     ActionController::RoutingError:
       No route matches {:controller=>"action_view/test_case/test", :action=>"/"}
Run Code Online (Sandbox Code Playgroud)

不过,我绝对可以访问浏览器中的/和其他资源.设置rspec时有什么我可以错过的吗?我把它放入Gemfile并运行rspec:install.

谢谢你,MrB

编辑:这是我的测试

  1 require 'spec_helper'
  2 
  3 describe "resource" do
  4   describe "GET" do
  5     it "contains /" do
  6       get "/"
  7       response.should have_selector("h1", :content => "Project")
  8     end
  9   end
 10 end
Run Code Online (Sandbox Code Playgroud)

这是我的路线档案:

myApp::Application.routes.draw do

  resources :groups do
    resources :projects
  end 

  resources :projects do
    resources :variants
    resources :steps

    member do
      get 'compare'
    end 
  end 

  resources :steps do
    resources :costs
  end 

  resources :variants do
    resources :costs
  end 

  resources :costs

  root :to => "home#index"

end
Run Code Online (Sandbox Code Playgroud)

我的spec_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'    

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|

  config.mock_with :rspec
  config.include RSpec::Rails::ControllerExampleGroup


  config.fixture_path = "#{::Rails.root}/spec/fixtures"


  config.use_transactional_fixtures = true
end
Run Code Online (Sandbox Code Playgroud)

我想,这里没有改变任何东西.

nat*_*vda 4

据我所知,您正在尝试将两个测试合并为一个。在 rspec 中,这应该分两步解决。在一种规范中,您测试路由,在另一种规范中,您测试控制器。

所以,添加一个文件spec/routing/root_routing_spec.rb

require "spec_helper"

describe "routes for Widgets" do
  it "routes /widgets to the widgets controller" do
    { :get => "/" }.should route_to(:controller => "home", :action => "index")
  end
end
Run Code Online (Sandbox Code Playgroud)

然后添加一个文件spec/controllers/home_controller_spec.rb,我正在使用由shoulda或卓越定义的扩展匹配器。

require 'spec_helper'

describe HomeController do

  render_views

  context "GET index" do
    before(:each) do
      get :index
    end
    it {should respond_with :success }
    it {should render_template(:index) }

    it "has the right title" do
      response.should have_selector("h1", :content => "Project")
    end

  end
end  
Run Code Online (Sandbox Code Playgroud)

实际上,我几乎从不使用render_views但总是尽可能隔离地测试我的组件。我在视图规范中测试视图是否包含正确的标题。

使用 rspec,我分别测试每个组件(模型、控制器、视图、路由),并使用 Cucumber 编写高级测试来切片所有层。

希望这可以帮助。