Anonymous controller in Minitest w/ Rails

孤者浪人 提交于 2019-12-19 04:47:41

问题


While converting from RSpec to Minitest I ran into a slight issue that Google has not helped with one bit, and that's figuring out how to do something like this:

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

with Minitest. Is there a way to create anonymous controllers like this inside of Minitest or is there documentation that could help me learn how to test controllers with minitest?


回答1:


I don't think anonymous controllers are supported. Instead of using a DSL to create a controller, try defining a controller in your test.

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



回答2:


You can do something like that:

# 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


来源:https://stackoverflow.com/questions/12832909/anonymous-controller-in-minitest-w-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!