gpt4 book ai didi

ruby-on-rails - 如何为 MiniTest 包含模块

转载 作者:行者123 更新时间:2023-12-03 17:39:35 25 4
gpt4 key购买 nike

我有课Companyinclude GrowthRate .

模型/公司.rb

class Company < ActiveRecord::Base
include GrowthRate
end

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

模型/公司/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的方法。

测试/模型/公司/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_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

最佳答案

您需要使用 ActiveSupport包含 block 。

对于您的示例,我想它找不到您在任何地方都不需要该文件的方法 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 中。

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

关于ruby-on-rails - 如何为 MiniTest 包含模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com