ruby-on-rails - Minitest-测试 Controller 问题

标签 ruby-on-rails ruby testing rspec minitest

我尝试使用minitest-rails并结合以下技术来测试 Controller 问题:

http://ridingtheclutch.com/post/55701769414/testing-controller-concerns-in-rails

Anonymous controller in Minitest w/ 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?中? (是的,这是一个糟糕的解决方案,但是如果有人发现更好的方法,我将在此保留)。

关于ruby-on-rails - Minitest-测试 Controller 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25937260/

相关文章:

ruby-on-rails - 每次我在 Rails 3 上遇到异常时都可以执行一个方法吗?

ruby-on-rails - 使用 Thin 运行的 Rails 应用程序 (Redmine) 中的权限被拒绝

css - 在 Rails 中应该使用什么作为 Sprite 生成器?

java - 我应该用什么文件名来测试我的应用程序?

java - 如何以及是否使用 Pact 测试句法(错误请求)验证?

ruby-on-rails - 从数据库中删除头像

ruby - 为什么 begin-next-end 的行为在 ruby​​ 和 jruby 中不同?

ruby - 正则表达式有助于跳过第一次出现的特殊字符,同时允许后面出现特殊字符但不允许空格

ruby - 如何转换 slim 到 html?

python - 如何在 Django 测试中强制交易中的竞争条件?