Skip to main content

Check if class was instantiated and instance method was called

Testing • Asked by Alex Musayev

Hey guys! I'd like to figure out a way to test piece of code that suppose to create an instance of particular class. Here is an example:

class Subject
  def call
    ...
  end
end

class Executor
  def action
    Subject.new.call
  end
end

class ExecutorTest < Minitest::Test
  def test_subject_was_instantiated
    # How to ensure that Subject instance was created?
  end

  def test_subject_was_called
    # How to ensure that Executor send :call message to Subject instance?
  end
end

I guess, I'm missing some concept or testing pattern here. Any advice?


I figured out the solution. Here are basic concepts:

1. To check if an instance method was called, it is possible to use a mock. For example, Minites::Mock.

2. To make sure a piece of code (Executor#action in the example above) performs a call to a class/instance method (Subject#call), it is possible to replace target method with a stub. Minitest library provides Object#stub method for this.

3. Testing logic can be simplified if Executor will be implemented with dependency injection in mind. So it relation between Executor and Subject will not be hardcoded, but configurable in runtime.

See also:

- https://semaphoreci.com/community/tutorials/mocking-in-ruby-with-minitest
- http://rubyblog.pro/2016/10/ruby-dependency-injection
- http://solnic.eu/2013/12/17/the-world-needs-another-post-about-dependency-injection-in-ruby.html
- https://medium.com/@Bakku1505/introduction-to-dependency-injection-in-ruby-dc238655a278


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.