How to write a specification for class methods that are called when the class is loaded?

class A include Logging log_to 'whatever' end 

I want to check if the log_to method is log_to with the correct parameter. But, as you might have guessed, the log_to method comes from the log module and is called when the class is loaded. How to write a specification or a custom match to check if a call to log_to 'whatever' ?

Even if I make fun of the log_to method on class A , there is no way in the specification to see if it will be called when it is called during class loading. I tried to remove the constant and load it again, which does not seem to work. Thoughts?

+4
source share
2 answers

This should probably be in a separate spec file from the spec file, which checks the bulk of the functions of class A:

 describe 'A' do it 'should log when loaded' do class A ; end A.should_receive(:log_to).with('whatever') require 'a' end end 

I would think, however, change the behavior of the class to something easier to test. Tests that are unusual in their design or that have complex limitations are also code smells.

+3
source

You should check the desired result, not the implementation details. I would check the Logging module in isolation as follows:

 describe Logging do TEST_IO = StringIO.new # some stub class for testing class Person include Logging log_to TEST_IO def name "Bob" end end after do TEST_IO.reopen end it "logs a method call to the given io" do person = Person.new TEST_IO.string.should eq("") person.name TEST_IO.string.should eq("name called\n") end # ... end 

And I'm not sure that I will test a real class that uses this module in general, because it is very simple and contains any dangerous logic. Random errors, such as syntax errors, will be caught by the integration test.

+1
source

Source: https://habr.com/ru/post/1391647/


All Articles