2017 Archives

Replacing Mocks With Hand-Written Test Doubles

— Tags: Ruby Pigeon, Ruby, Testing

Consider the following test.

RSpec.describe Commands::StartRecording do
  it "spawns one recording process per camera" do
    expect(ProcessManager).to receive(:spawn).with(/camera_11/).and_return(123)
    expect(ProcessManager).to receive(:spawn).with(/camera_22/).and_return(456)
    allow(ProcessManager).to receive(:exists?).with(123).and_return(true)
    allow(ProcessManager).to receive(:exists?).with(456).and_return(true)

    result = Commands::StartRecording.(cameras: [11, 22])

    expect(result).to be_successful
  end

  # (more tests here)
end

I will be using RSpec in this article, but the concept applies equally well to Minitest.

This test checks that Commands::StartRecording spawns multiple processes via ProcessManager. We don’t want to actually spawn any processes during testing, so methods on ProcessManager have been mocked out using RSpec Mocks.

There are a few problems with this test.

Super Secret Methods

— Tags: Ruby Pigeon, Ruby

Here is a quirk of the Ruby language that I discovered a few weeks ago.

Method names can not contain a period character.

def secret.squirrel
  :shhh
end
#=> undefined local variable or method `secret' (NameError)

This is because the period character is syntax used for defining methods on specific objects.

secret = "hello"
def secret.squirrel
  :shhh
end

p secret #=> "hello"
p secret.squirrel #=> :shhh

Even though the syntax does not allow periods in the method name, surprisingly, the Ruby runtime will allow it. Using define_method, the syntax limitations can be bypassed.

# this works
define_method('secret.squirrel') do
  :shhh
end

The method above can’t be called using normal Ruby syntax.

secret.squirrel
#=> undefined local variable or method `secret' (NameError)

But again, the syntax limitations can be bypassed, using send.

p send('secret.squirrel') #=> :shhh

To summarize, it is possible to define and call methods that are impossible to access via normal Ruby syntax.

Result Objects - Errors Without Exceptions

— Tags: Ruby Pigeon, Ruby

In Ruby, errors and failures are typically implemented with exceptions. In some situations, however, exceptions may not be the best choice. This article covers some of the problems with exceptions, and introduces a functional, alternative approach to error handling.