Mocking constructors in Ruby

I am a Java developer playing with and loving with Ruby. I realized that due to the Ruby metaprogramming capabilities, my unit tests are getting a lot cleaner and I don’t need any unpleasant mocking frameworks. I have a class that needs class services File, and in my test I don’t want to touch my real file system. In Java, I would use some virtual file system for simpler “seams” to skip fake objects, but in Ruby, which are clearly overdone. What I came up with seems to be really pretty compared to the Java world. In my class under testing, I have an optional constructor parameter:

def initialize(file_class=File)

When I need to open files in my class, I can do this:

@file_class.open(filename)

And the call goes either to the real file class, or in the case of my unit test, it goes to a fake class that does not concern the file system. I know there should be a better way to do this with metaprogramming?

+3
source share
3 answers

Mocha ( http://mocha.rubyforge.org/ ) is a very good mocking library for ruby. Depending on what you really want to test (i.e. if you just want to fake a call to File.new to avoid a file system dependency or if you want to check that the correct arguments are passed to File.new), you can do something like this:


require 'mocha'

mock_file_obj = mock("My Mock File") do
  stubs(:some_instance_method).returns("foo")
end

File.stubs(:new).with(is_a(String)).returns(mock_file_obj)

+11
source

, , , , , . , , ( ). . , ( , )

+1

This is a difficult task for me. With the help of this question I received and some additional work on my behalf, here is the solution I came to.

# lib/real_thing.rb
class RealThing
  def initialize a, b, c
    # ...
  end
end

# test/test_real_thing.rb
class TestRealThing < MiniTest::Unit::TestCase

  class Fake < RealThing; end

  def test_real_thing_initializer
    fake = mock()
    Fake.expects(:new).with(1, 2, 3).returns(fake)
    assert_equal fake, Fake.new(1, 2, 3)
  end

end
+1
source

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


All Articles