Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include module for MiniTest

I have a class Company that include GrowthRate.

models/company.rb

class Company < ActiveRecord::Base
  include GrowthRate
end

In the growth_rate.rb, I add some methods for 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

And I want to test the method of Array by MiniTest.

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

But the test ends up with a name error.

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

How can I include the method for 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
like image 519
ironsand Avatar asked Nov 19 '22 18:11

ironsand


1 Answers

You'll want to use the ActiveSupport included block.

For your example, I imagine it can't find the method b/c you're not requiring that file anywhere.

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 also doesn't autoload these, so you'll need to make sure they're included in a require in each test or in the test_helper.

If you need me to break this down more, please ask.

like image 87
Kevin Brown Avatar answered Jan 06 '23 06:01

Kevin Brown