Andrew
Andrew

Reputation: 238667

How to use RSpec to test a Sinatra application within a gem?

I am writing a gem which includes a Sinatra application that a developer can extend. For example:

# gem code:
require 'sinatra'
module Mygem
  class Application < Sinatra::Base
    get 'auth/login' {}
    get 'auth/logout {}
  end
end

# developer code:
require 'mygem'
class DeveloperApp < Mygem::Application
  # ..
end

I am also getting started using RSpec. How should I configure RSpec for testing this functionality?

Upvotes: 4

Views: 2180

Answers (3)

Rimian
Rimian

Reputation: 38418

Be sure to include the rack-test gem.

You spec helper should have:

require 'rack/test'
require 'foo' # or where ever your app is

# This can go in a helper somewhere
module AppHelper
  def app
    Foo.new
  end
end

RSpec.configure do |config|
  config.include Rack::Test::Methods
  config.include AppHelper
end

Then, your spec can be as follows:

require 'spec_helper'

# Example app. Delete this example.
class Foo < Sinatra::Base
   get '/' do
    'Jesse Pinkman'
  end
end

describe Foo do
  it 'is testable' do
    get '/' do
      expect(last_response).to be_ok
    end
  end
end

Upvotes: 0

Dave Syer
Dave Syer

Reputation: 58094

The references above are all informative and useful but mostly rails specific. I found it quite hard to find a simple recipe for a basic test of a modular Sinatra app, so I am hoping this will answer the question for others. Here is a completely bare-bones, small as possible test. This is probably not the only way to do it, but it works well for a modular app:

require 'sinatra'
class Foo < Sinatra::Base
   get '/' do
    "Hello"
  end
end

require 'rack/test'

describe Foo do

  include Rack::Test::Methods

  def app
    Foo.new
  end

  it "should be testable" do
    get '/'
    last_response.should be_ok
  end

end

Note that there is no need to have the server running when you launch the test (some tutorials I saw implied that you do) - it's not an integration test.

Upvotes: 5

danieltahara
danieltahara

Reputation: 4993

It's actually pretty simple -- just add rspec to your gemfile (then bundle install), and make a directory in your gem called spec/. Once you've done that, add a file spec/spec_helper.rb that contains some configuration for rspec (mostly requiring various files from your library) as well as defining some helper methods for your specs. Then, for each model and controller, make a file called my_model_name_spec.rb or my_controller_name_spec.rb, and do the test there.

Here are some useful resources for getting started with rspec:

Railscasts:

http://railscasts.com/episodes/275-how-i-test

http://railscasts.com/episodes/71-testing-controllers-with-rspec

http://railscasts.com/episodes/157-rspec-matchers-macros/

And for some more advanced (but well-explained) stuff:

http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks

Upvotes: 0

Related Questions