3

I'm relatively new to Sinatra, and I want to figure out a way to integrate RSpec with my Sinatra setup.

config.ru

require 'sinatra' require 'mongoid' require 'uri' require './lib/twilio_wrapper' Mongoid.load!("./config/mongoid.yml") Dir["./controllers/*.rb"].each { |file| require file } run Rack::URLMap.new( '/' => HomeController.new, '/users' => UsersController.new(TwilioWrapper.new) ) 

With this setup, I can modularize my controllers and create single instances of helper classes (such as TwilioWrapper). However, if I want to set up RSpec, I need to point it to my application's class. However, in the situation above, because I'm using Rack::URLMap, I don't have a specific application class to point RSpec to.

How can I keep my code modular in the fashion outlined above while including RSpec for tests?

1 Answer 1

3

Rack does not care about controllers, it cares about apps. So HomeController and UsersController are 2 Sinatra applications "racked up" in Rack. These are not controllers, they are separate Rack apps. I do not think you want 2 applications but rather to put these 2 controllers in 2 files so you can spec them out separately and keep the code readable.

The naming convention for Sinatra is to name it something like MyApp to reflect this. Sinatra is a flat framework, but you can name your "controller" files what you want.

So in folder routes you can have 'users.rb' and 'home.rb' but both files have at the top

MyApp < Sinatra::Application 

Then you can test using Rack::Test with Rspec.

If you do indeed want to test 2 apps and want the prefix using Rack::Test w Rspec you simply need to define app in your spec_helper or spec file as:

 def app run Rack::URLMap.new( '/' => HomeController.new, '/users' => UsersController.new(TwilioWrapper.new) ) end 

All Rack::Test does is rackup your Sinatra app into a test container.

Also please see Phrogz's excellent answer on how to lay out a Sinatra application

Sign up to request clarification or add additional context in comments.

1 Comment

Great explanation. I think what I really needed in the end was the link to an example Sinatra app. I'm going to do a little bit of refactoring, and I should be good to go.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.