I mentioned last week that I had started building a Sinatra app and had some luck getting my first Cucumber tests running with the help of a Nettuts tutorial and 200 lines of “free” step definitions from the cucumber-sinatra gem. Since this was my first dive into Sinatra and Cucumber I was a little leary of going carte blanche with the gem. Fortunately on a second run I was able to get it working with my own step definitions and then I was also able to get Rspec up and running too. Here’s the main steps in case anyone wants to give this a shot.

Gemfile

Easy peasy.

source "http://rubygems.org"
gem "sinatra"
gem "cucumber"
gem "capybara"
gem "rspec"

File Structure

Below is the file structure of my app, called ‘Foundry’. The important files to note for the Cucumber setup are the 'features’ directory and all its files, which is the usual location for the Cucumber files. The important RSpec files are in their usual place too in the 'spec’ folder. (You can ignore the 'interactors’ and 'memory_objects’ folders, those are another ball of wax I’m working on.)

Cucumber 'env.rb’ File

This is the important file for wiring Cucumber up to the app and it tells Cucumber where and what everything is. This file goes inside 'features/support’. The first line uses Micah’s guidelines for requiring our main app file. The next three lines require the three gems Cucumber needs, and the final 'World do’ block is specific to Cucumber. In a Rails app the cucumber gem automatically sets this up but we need to do it manually in Sinatra

#where foundry below is the name of your main app file
require File.join(File.expand_path(File.dirname(__FILE__)),'../../foundry')

require "Capybara"
require "Capybara/cucumber"
require "rspec"

World do
Capybara.app = Foundry #where Foundry is the class in your main app file

include Capybara::DSL
include RSpec::Matchers
end

RSpec 'spec_helper’ File

And here’s all the wiring for RSpec to your app, which goes right inside the spec folder. Again, in the first line I’m telling it where everything is. The comments in the code explain the last two blocks.

require File.join(File.expand_path(File.dirname(__FILE__)), '/../', 'foundry')

require 'sinatra'
require 'rack/test'

set :environment, :test

#specify that the app is a Sinatra app
def app
Sinatra::Application
end

#make Rack::Text available to all spec contexts
RSpec.configure do |config|
config.include Rack::Test::Methods
end

And there you have it. With that setup you can start running Cucumber tests on your main app file and RSpec tests on your main app file as well as anything in your lib directory (with the standard require statement). If you’d like to read more these posts were pretty helpful: