Testing en Sinatra

  1. Build a Sinatra API Using TDD, Heroku, and Continuous Integration with Travis by Darren Jones. Published December 9, 2013 SitePoint
  2. Código del artículo anterior
  3. Mini MiniTest Tutorial by Tim Millwood

    We'll use MiniTest::Spec, which is a functionally complete spec engine, to create a spec for a Hello World! Sinatra application. Firstly we create a folder 'spec' within the application directory. Within this, two files.

    ENV['RACK_ENV'] = 'test'
    
    require 'minitest/autorun'
    require 'rack/test'
    require_relative '../app'
    
    include Rack::Test::Methods
    
    def app
      Sinatra::Application
    end
    

    The above code is to go into the file spec_helper.rb. It sets up the initial setting for the test. We set the RACK_ENV environment variable to 'test' then require 'minitest/autorun' for MiniTest, 'rack/test' because we are testing a rack based application and our application, in this case app.rb. The Rack::Test::Methods module is included to add a number of helper methods to allow the testing of rack applications. Finally we define the application as a Sinatra Application. The next file app_spec.rb will be our spec.

    require_relative 'spec_helper'
    
    describe 'Hello World' do
    
      it 'should have hello world' do
        get '/'
        last_response.must_be :ok?
        last_response.body.must_include "Hello world!"
      end
    end
    
    Firstly the spec_helper file is required, we then create a describe block to describe the 'Hello World' application. Within this a single behaviour. We run a get method against the root route and check the response is ok, and that the page includes the text 'Hello World!'.

Casiano Rodríguez León
2015-01-25