【问题标题】:How to create a route for testing purposes?如何创建用于测试目的的路线?
【发布时间】:2013-11-13 21:15:50
【问题描述】:

我正在使用 rspec 为我的 rails 应用程序(用 Rails 4 编写)中的应用程序控制器编写测试,我遇到了一个问题,它无法识别我发送的 HTTP 请求的路由。我知道有一种方法可以使用 MyApp::Application.routes 来做到这一点,但我无法让它工作。

#application_controller_spec.rb

require 'spec_helper'


class TestController < ApplicationController

  def index; end

end

describe TestController do
  before(:each) do
    @first_user = FactoryGirl.create(:user) 
      # this is to ensure that all before_filters are run
    controller.stub(:first_time_user)
    controller.stub(:current_user)
end

describe 'first_time_user' do
  before(:each) do
    controller.unstub(:first_time_user)
  end

  context 'is in db' do
    before(:each) do
      @user = FactoryGirl.create(:user)
      controller.stub(:current_user).and_return(@user)
    end

    it 'should not redirect' do
      get :index
      response.should_not be_redirect
    end
  end

  context 'is not in db' do

    context 'session[:cas_user] does not exist' do
      it 'should return nil' do
        get :index
        expect(assigns(:current_user)).to eq(nil)
      end
    end

    it "should redirect_to new_user_path" do
      controller.stub(:current_user, redirect: true).and_return(nil)
      get :index
      response.should be_redirect
    end
  end
end

我现在遇到的错误是

No route matches {:action=>"index", :controller=>"test"}

我会将 test#index 路由添加到 config/routes.rb,但它无法识别测试控制器,所以我想做类似的事情

MyApp::Application.routes.append do
  controller :test do
    get 'test/index' => :index
  end
end

但我不确定在哪里添加它,或者它是否适用于 rspec。任何帮助都会很棒!

【问题讨论】:

  • 你是什么意思:“我会将 test#index 路由添加到 config/routes.rb,但它无法识别测试控制器”??将路由添加到 routes.rb 并从终端执行“rake routes”并检查输出。可能是单数/复数和控制器名称的生成问题。
  • 抱歉,不清楚——当我 rake 路由时,它会抛出“rake aborted!missing :controller”问题是测试控制器只存在于文件“application_controller_spec.rb”中跨度>

标签: ruby-on-rails rspec applicationcontroller


【解决方案1】:

如果您正在尝试测试您的 ApplicationController,请参阅此RSpec documentation。您需要在测试中定义 index 之类的方法,但效果很好。

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多