【问题标题】:Rails: How to test a controller with routes defined via a scope?Rails:如何使用通过范围定义的路由来测试控制器?
【发布时间】:2012-11-28 08:47:15
【问题描述】:

给定路线:

  scope :path => 'shipping_reports', :controller => 'ShippingReports', :as => 'shipping_reports' do
    get 'index'
  end

以及以下测试:

class ShippingReportsControllerTest < ActionController::TestCase
 test "routing" do
    assert_routing '/shipping_reports/index', { :controller => "ShippingReports", :action => "index" }
  end

  test 'index' do
    get :index
    assert_response :success
 end
end

第一次测试通过,第二次失败:

ActionController::RoutingError: No route matches {:controller=>"shipping_reports"}

有人知道我怎样才能通过测试吗?

【问题讨论】:

  • 我发现如果删除了“路由”测试,“索引”测试就会起作用。我不明白为什么我自己会成为一个问题!如果我找出原因,我会更新帖子......

标签: ruby-on-rails routes functional-testing


【解决方案1】:

我设法完成这项工作的唯一方法是将我的路线更改为:

controller 'shipping_reports', :path => '/shipping_reports', :as => 'shipping_reports'

它读起来更好,测试通过了,但我仍然想知道如何测试问题路线......

【讨论】:

  • 嗨,我遇到了完全相同的问题...您找到原始问题的答案了吗?谢谢!
  • 不,对不起@AL,因为上面的答案实际上更好,我不再寻找答案。我已经浪费了很多时间了:(
【解决方案2】:

有一个非常相似的问题。

给定路线:

  scope ":client" do
    resources :categories, as: :client_categories
  end

我必须做到以下几点:

test '#update' do
  put :update, { params: { id: cat.id, client: client } } # => error
  put :update, { params: { id: cat.id, } }, { client: client } # => OK
end

【讨论】:

    【解决方案3】:

    遇到了类似的问题。我所做的是对测试路线上的 rails 预定义路径。

    查看下面的测试修改

    class ShippingReportsControllerTest < ActionController::TestCase
     test "routing" do
        assert_routing index_path, { :controller => "ShippingReports", :action => "index" }
      end
    
      test 'index' do
        get index_path #the actual path to the index controller
        assert_response :success
     end
    end
    

    N:B 你可以在 localhost http://localhost:3000/rails/info/routes 的路由列表上获取路径名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多