Ask A Question

Notifications

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
    ...
  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?

Reply
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

Reply
Join the discussion
Create an account Log in

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

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

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