Sinatra – RSpec integration without a patch. With Examples
After my half-assed post about RSpec testing the Sinatra framework got several google hits, I figured I’d look into it a little further. Here’s what I found.
First, a very simple Sinatra application.
$:.unshift("../sinatra/lib") require 'sinatra' get '/' do "Hello" end get '/:thingy' do "Hello #{params[:thingy]}" end
Now a test script.
$:.unshift("../sinatra/lib") require 'sinatra' require 'spec/interop/test' require 'sinatra/test/unit' describe 'Hello World' do require 'hello' specify "should render hello at /" do get_it '/' @response.should be_ok @response.body.should == "Hello" end specify "should render argument at /anything" do get_it '/foo' @response.should be_ok @response.body.should == "Hello foo" get_it '/bar' @response.should be_ok @response.body.should == "Hello bar" end specify "should not respond to nested paths" do get_it '/foo/bar' @response.should_not be_ok end end
What I did - basically, all that needed to be done was to bypass the ‘sinatra/test/spec’ file, which in turn requires the test/spec library, which we need to avoid.
Instead, we require the RSpec interop library, and then get the ‘sinatra/test/unit’ file, which sets up a reasonable environment to start testing, including deferring to ‘sinatra/test/methods’ to define the helpers like ‘get_it’, ‘post_it’ and so on. The bonus is that you get to skip the require of test/spec, and get to stick to pure RSpec.
Where to go from here - I would like some input on what other helpers would be cool/useful. I haven’t worked with RSpec all that much (well.. at all), so I don’t know what’s helpful, and what’s not. Leave comments, or hit me up on IRC.
May 29th, 2008 at 1:14 am
Good stuff. I personally prefer test/spec but rspec is requested every so often in #sinatra.
I’m wondering: are the explicit @response references required with rspec for some reason? Everything gets forwarded to @response automatically with the built-in stuff. e.g., instead of:
specify "should render hello at /" doget_it '/'
@response.should be_ok
@response.body.should == "Hello"
end
You should be able to:
specify "should render hello at /" doget_it '/'
should be_ok
body.should == "Hello"
end
I think all of the plumbing to make that work is in ‘sinatra/test/unit’ (or maybe ‘sinatra/test/methods’)…
May 29th, 2008 at 7:16 am
You know, I tried it, and it didn’t work. I didn’t dig much further than that though.
July 29th, 2008 at 11:11 pm
[…] turns out that RSpec takes a little bit of manual work to get going with Sinatra. I read a helpful article on gittr.com that pointed me in the right direction. The article advised me to add these lines to my spec […]