[英]Minitest - test controller concerns
我嘗試使用 minitest-rails 並結合以下技術來測試我的控制器問題:
http://ridingtheclutch.com/post/55701769414/testing-controller-concerns-in-rails 。
我得到“沒有路由匹配錯誤”: ActionController::UrlGenerationError: 沒有路由匹配 {:action=>"index", :controller=>"fake"}
require "test_helper"
require "warden_mock"
class FakeController < ApplicationController
attr_accessor :request
def initialize(method_name=nil, &method_body)
include MyConcern # method redirect_to_404 placed here
@request = OpenStruct.new # mockup request
@request.env = {}
@request.env['warden'] = WardenMock.new # mockup warden
if method_name and block_given? # dynamically define action for concern methods testing
self.class.send(:define_method, method_name, method_body)
test_routes = Proc.new do
resources :fake
end
Rails.application.routes.eval_block(test_routes)
end
end
end
describe FakeController do # just very simple test
context "just redirect_to_404" do
it "it must redirect to /404" do
@controller = FakeController.new(:index) { redirect_to_404 }
get :index
assert_redirected_to '/404'
end
end
end
我有 rails 4.1.5 和 minitest 5.4.0
對於 OP 來說可能為時已晚,但我是這樣做的:
require 'test_helper'
class SolrSearchParamsFakeController < ApplicationController
include SolrSearchParams # this is my controller's concern to test
def index
# The concern modify some of the parameters, so I'm saving them in a
# variable for future test inspection, so YMMV here.
@params = params
render nothing: true
end
end
Rails.application.routes.draw do
# Adding a route to the fake controller manually
get 'index' => 'solr_search_params_fake#index'
end
class SolrSearchParamsFakeControllerTest < ActionController::TestCase
def test_index
get :index, search: 'asdf wert'
# finally checking if the parameters were modified as I expect
params = assigns(:params)
assert_equal params[:original_search], 'asdf wert'
end
end
抱歉,但實際上這在某種程度上搞亂了我所有涉及路由訪問的測試,就像Rails.application.routes.draw
一樣,我正在重寫所有測試路由,只留下solr_search_params_fake#index
路由。
不知道如何添加而不是重寫....一個修復將直接添加到config/routes.rb
我的測試路由與一個if Rails.env.test?
健康)狀況? (是的,這是一個糟糕的解決方案,但我會把它留在這里,以防有人找到更好的方法來做到這一點)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.