【问题标题】:how to include module for MiniTest如何为 MiniTest 包含模块
【发布时间】:2016-09-13 00:50:29
【问题描述】:

我有一个Company 的课程include GrowthRate

models/company.rb

class Company < ActiveRecord::Base
  include GrowthRate
end

growth_rate.rb中,我为Array添加了一些方法。

models/company/growth_rate.rb

module Company::GrowthRate
  extend ActiveSupport::Concern
end

module Company::GrowthRate::Array
  def growth_rate
    # calculate growth rate
  end
end

class Array
  include Company::GrowthRate::Array
end

我想通过MiniTest测试Array的方法。

test/models/company/growth_rate_test.rb

require 'test_helper'

class CompanyTest < ActiveSupport::TestCase
  include Company::GrowthRate
  test 'test for adjusted_growth_rate' do
    array = [1, 0.9]
    Array.stub :growth_rate, 1 do
      # assert_equal
    end
  end
end

但测试以名称错误结束。

NameError: undefined method `growth_rate' for `Company::GrowthRate::Array'

如何包含 MiniTest 的方法?

test/test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'minitest/mock'
class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
end

【问题讨论】:

  • 您在测试growth_rate 方法吗?如果是,为什么会被存根?
  • 对不起,测试是针对def adjusted_growth_rate,所以我想存根growth_rate。我改变了问题。
  • 您是否尝试过包括:require 'test_helper'?还有,test/test_helper.rb 的内容是什么?
  • 是的,我需要test_helper,并在我的问题中添加了它的内容。

标签: ruby-on-rails minitest


【解决方案1】:

您需要使用 ActiveSupport 包含的块。

对于您的示例,我想它找不到您在任何地方都不需要该文件的方法 b/c。

module PolymorphicTest
  extend ActiveSupport::Concern

  included do
    test 'some cool polymorphic test' do
      assert private_helper_method
    end


    private

    def private_helper_method
      # do stuff
    end
  end
end

Minitest 也不会自动加载这些,因此您需要确保它们包含在每个测试中的require test_helper 中。

如果您需要我进一步分解,请询问。

【讨论】:

    【解决方案2】:

    我认为您必须将 models/company/growth_rate.rb 移动到 app/model/concerns 文件夹中,文件名 = 'growth_rate.rb'

    那就不要使用 Company 类来防止类名冲突

    module GrowthRate
      extend ActiveSupport::Concern
    
      # ...
    end
    

    现在您可以将其包含到您的公司模型中

    然后在 config/initializers 文件夹中创建 array.rb 文件,其中包含

    class Array
      def growth_rate
        # calculate growth rate
      end
    end
    

    这个文件只会被rails加载一次,如果你想添加自定义方法到Array类是很好的

    现在您可以从 test/models/company/growth_rate_test.rb 中删除 include Company::GrowthRate

    【讨论】:

    • 我曾经使用concerns 文件夹,但它混淆了所有关注文件,所以我找到了像现在这样的地方。没有类名冲突。我添加了一个这样的新方法,以便在发生错误时可以轻松地跟踪堆栈跟踪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2015-07-17
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多