在插件测试中模拟Rails 3路由和控制器的正确方法是什么?

时间:2011-05-11 21:24:22

标签: ruby ruby-on-rails-3 testing routes ruby-on-rails-plugins

我有一个旧的预Rails 3插件,其测试将不再在Rails 3下运行。测试看起来像这样:

class TestController < ActionController::Base
  def test_action; render :nothing => true; end
end

TestController.view_paths = [File.dirname(__FILE__)]

ActionController::Routing::Routes.draw {|m| m.connect ':controller/:action/:id' }

class TestControllerTest < ActionController::TestCase
  context "test_action" do
    should "do something" do
      lambda { post :test_action }.should change { Model.count }
    end
  end
end

运行此测试让我:

  

未初始化的常量ActionDispatch :: Routing :: Routes(NameError)

当我使用with_routing时,我认为是进行测试路由的新方法,如下所示:

should "do something" do
  with_routing do |set|
    set.draw { |m| m.connect ':controller/:action/:id' }
    lambda { post :test_action }.should change { Model.count }
  end
end

我明白了:

  

NameError:未定义的局部变量或TestController的方法`_routes:Class

我错过了什么?我的测试助手需要:

require 'rubygems'
require 'active_record'
require 'active_record/version'
require 'active_record/fixtures'
require 'action_controller'
require 'action_dispatch'
require 'action_view'
require 'test/unit'
require 'shoulda'
require 'mocha'

想法?谢谢!

2 个答案:

答案 0 :(得分:0)

您只需要在Rails.application上绘制路线

Rails.application.routes.draw do
  # Fun times
end

答案 1 :(得分:0)

编辑:呃,对不起,这在rails 3上不起作用,但是你可能已经升级了吗?

https://relishapp.com/rspec/rspec-rails/v/3-6/docs/controller-specs/engine-routes-for-controllers

您没有指定任何测试框架,所以我只想提一下,RSpec在routestype: :controller规范中为您提供了type: :routing方法,因此您可以执行类似

before do
  routes.draw do
    get  ':controller/:action/:id' => 'controller#action' 
  end
end