Jan 13 2008

Using Synthesis with Expectations

This example builds on the test project described in Using Synthesis with Test::Unit and Mocha. Instead of a combination of Test::Unit and Mocha, we will be using Synthesis in conjunction with the Expectations lightweight testing framework.

Synthesis comes with an Expectations adapter. The rake task looks like this:

Rakefile:

require "rubygems"
require "synthesis/task"

task :default => 'synthesis:test'
Synthesis::Task.new do |t|
  t.adapter = :expectations
end

Following are the project's tests, rewritten with the Expectations library.

data_brander_test.rb:

require "rubygems"
require "expectations"
require File.dirname(__FILE__) + "/../lib/synthesis_example"

Expectations do
  expect Storage.new('yep').to_receive(:save).with('METAL - rock') do |s|
    DataBrander.new(s).save_branded 'rock'
  end
end

Running this test will produce:

Macintosh-4:synthesis_example gm$ ruby test/data_brander_test.rb
Expectations .
Finished in 0.001 seconds

Success: 1 fulfilled

Because we haven't yet written a test for the simulated save method on the mocked Storage instance, the Synthesis Rake task will fail.

Macintosh-4:synthesis_example gm$ rake synthesis:test
(in /Users/gm/devel/ruby/whatever_code/synthesis_example)
[Synthesis] Collecting expectations...
Expectations .
Finished in 0.001 seconds

Success: 1 fulfilled
[Synthesis] Verifying expectation invocations...
Expectations .
Finished in 0.001 seconds

Success: 1 fulfilled
[Synthesis]
[Synthesis] Tested Expectations:
[Synthesis]
[Synthesis] Untested Expectations:
[Synthesis] Storage.new.save
[Synthesis]
[Synthesis] Ignoring:
[Synthesis]
[Synthesis] FAILED.

Writing a test for the concrete implementation of Storage.new.save fixes the issue.

storage_test.rb:

require "rubygems"
require "expectations"
require File.dirname(__FILE__) + "/../lib/synthesis_example"

Expectations do
  expect "rock" do
    begin
      Storage.new('test.txt').save('rock')
      File.read 'test.txt'
    ensure
      FileUtils.rm_f 'test.txt'
    end
  end
end
Macintosh-4:synthesis_example gm$ rake synthesis:test
(in /Users/gm/devel/ruby/whatever_code/synthesis_example)
[Synthesis] Collecting expectations...
Expectations ..
Finished in 0.00199 seconds

Success: 2 fulfilled
[Synthesis] Verifying expectation invocations...
Expectations ..
Finished in 0.00174 seconds

Success: 2 fulfilled
[Synthesis]
[Synthesis] SUCCESS.