Minitest中的匿名控制器w / Rails

时间:2012-10-11 05:39:56

标签: ruby-on-rails-3 rspec minitest

在从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测试控制器?

2 个答案:

答案 0 :(得分:4)

你可以这样做:

# 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

答案 1 :(得分: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