3

在从 RSpec 转换到 Minitest 时,我遇到了一个小问题,谷歌一点也没有帮助,那就是弄清楚如何做这样的事情:

describe ApplicationController do
  controller do
    def index
      render nothing: true
    end
  end

  it "should catch bad slugs" do
    get :index, slug: "bad%20slug"
    response.code.should eq("403")
  end
end

与 Minitest。有没有办法在 Minitest 中创建像这样的匿名控制器,或者是否有文档可以帮助我学习如何使用 minitest 测试控制器?

4

2 回答 2

7

你可以这样做:

# Add at runtime an action to ApplicationController
ApplicationController.class_eval do
  def any_action
    render :nothing
  end
end

# If disable_clear_and_finalize is set to true, Rails will not clear other routes when calling again the draw method. Look at the source code at: http://apidock.com/rails/v4.0.2/ActionDispatch/Routing/RouteSet/draw
Rails.application.routes.disable_clear_and_finalize = true

# Create a new route for our new action
Rails.application.routes.draw do
  get 'any_action' => 'application#any_action'
end

# Test
class ApplicationControllerTest < ActionController::TestCase
  should 'do something' do
    get :any_action

    assert 'something'
  end
end
于 2014-10-28T09:30:06.287 回答
2

我认为不支持匿名控制器。尝试在测试中定义一个控制器,而不是使用 DSL 创建控制器。

class SlugTestController < ApplicationController
  def index
    render nothing: true
  end
end

describe SlugTestController do
  it "should catch bad slugs" do
    get :index, slug: "bad%20slug"
    response.code.must_equal "403"
  end
end
于 2012-10-11T06:17:39.510 回答