All threads / Check if class was instantiated and instance method was called
Ask A Question


You’re not receiving notifications from this thread.

Check if class was instantiated and instance method was called

Alex Musayev asked in Testing

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

class Executor
  def action

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

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

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:


Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 68,326+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.