Test your rake tasks

Reading Time: 2 minutes

I'll show you how to test a rake task in a simple Sinatra Bootstrap project. Here we will put YML files into the JSON format.

A few days ago I was pairing with a coworker, and we needed to convert a YML file into the JSON format because the output was going to be used with Jasmine. So, what to do?

First we need to create an Rspec file

$ touch rspec/tasks/yml2json_spec.rb

As you can see, the file was created in the rspec/tasks/ directory.

Next, we will start testing our rake task:

require 'rspec'
require 'rake'

describe 'setup namespace rake task' do
  describe 'setup:yml2json' do
    before do
      load "tasks/yml2json.rake"

    it "should returns json file" do
      expect(File.exists?('public/javascripts/from-yml-to-json.json')).to be_true

In your CLI write:

$ rspec

You will see this output:

Finished in 0.0005 seconds
1 example, 1 failure

Then, to make the previous test pass, we will create a file in our tasks/yml2json.rb directory:

namespace :setup do
  desc "Generate a json file according to yml_file.yml"
  task :yml2json do
    require 'yaml'
    require 'json'

    destination = "public/javascripts/from-yml-to-json.json"
    json = YAML.load_file('spec/yml_file.yml').to_json
    File.open(destination, 'w') do |file|
      file.write json

After this, go to the console again and type:

$ rspec

You will see this:

Finished in 0.0446 seconds
1 example, 0 failures

Now we need to load our rake task into our Rakefile:

require 'rubygems'
require 'bundler' 
require 'rake'

Dir["tasks/*.rake"].sort.each { |ext| load ext }

Don't forget to create your YML file into spec/yml_file.yml. That is the file that will be converted into the JSON format.

  one: "First Element"
  two: "Second Element"
  three: "Third Element"
  one: "First Element"
  two: "Second Element"
  three: "Third Element"

Now we run our task:

rake setup:yml2json

Voila! after that you will have this file in your directory: public/javascripts/from-yml-to-json.json

    "one":"First Element",
    "two":"Second Element",
    "three":"Third Element"
    "one":"First Element",
    "two":"Second Element",
    "three":"Third Element"}

What I used for this post:

I hope this was helpful, thanks for reading!

Follow me on Twitter @zazvick, read me at PolyglotCoder or mail me at victor.velazquez@magmalabs.io and stay in touch!

You May Also Like