SoEzPz
SoEzPz

Reputation: 15912

Test (rspec) a module inside a class (Ruby, Rails)

I have this to work with...

class LegoFactory # file_num_one.rb

  include Butter # this is where the module is included that I want to test.
  include SomthingElse
  include Jelly

  def initialize(for_nothing)
    @something = for_nothing
  end
end

class LegoFactory # file_num_2.rb
  module Butter

    def find_me
      # test me!
    end
  end
end

So, when LegoFactory.new("hello") we get the find_me method as an instance method of the instantiated LegoFactory.

However, there are quite a few modules includes in the class and I just want to separate the Butter module without instantiating the LegoFactory class.

I want to test ONLY the Butter module inside of the LegoFactory. Names are made up for this example.

Can this be done?

Note: I cannot restructure the code base, I have to work with what I have. I want to just test the individual module without the complexity of the rest of the LegoFactory class and its other included modules.

Upvotes: 0

Views: 255

Answers (1)

Jesuspc
Jesuspc

Reputation: 1734

A way to do it is to create a fake class that includes your module in order to test it:

describe LegoFactory::Butter do
  let(:fake_lego_factory) do
    Class.new do
      include LegoFactory::Butter
    end
  end
  subject { fake_lego_factory.new }

  describe '#find_me' do
    it 'finds me' do
      expect(subject.find_me).to eq :me
    end
  end
end

You can also implement in the fake class a mocked version of any method required by find_me.

Upvotes: 2

Related Questions