General

Gems

Web Based

Mountain Berry Fields

Testing Ruby Embedded in Documents Like Readmes

Because I write a lot of gems, I need to ensure that the examples in the readmes don't diverge from the code. I wrote Mountain Berry Fields to do this.

To use it, you must create a testing strategy. I provide two already, rspec, and magic_comments.

Say you had a readme like this Readme.mountain_berry_fields.md:

# MyLibName

It calculates some result

    <% test 'an example1', with: :magic_comments do %>
    MyLibName.new('some data').result # => "some cool result"
    <% end %>

Here it is in an RSpec test:

    <% test 'an example2', with: :rspec do %>
    describe MyLibName do
      it 'does what I made it do' do
        described_class.new('some data').result.should == 'some cool result'
      end
    end
    <% end %>

When you ran mountain_berry_fields Readme.mountain_berry_fields.md, it would generate Readme.md which looked like this

# MyLibName

It calculates some result

    MyLibName.new('some data').result # => "some cool result"

Here it is in an RSpec test:

    describe MyLibName do
      it 'does what I made it do' do
        described_class.new('some data').result.should == 'some cool result'
      end
    end

The first test block uses magic_comments, which look at the value to the right of the # =>, and check to see that it comes back the same as what you said it should be in your example. The second uses RSpec, guaranteeing the same thing.

Unless, of course, your code did not work, in which case, it would alert you to which test failed.

If neither of these test strategies work for you, you can write your own.

There are aslo context blocks, for when you want to render the code inside of a context that you don't care to include in the output, and setup blocks, for when some block of code needs to run before all the others (e.g. load up the library).

Code is on github.