Reputation: 11
How do I access the app instance so I can test the foobar() method?
class App < Sinatra::Base
get '/' do
return foobar
end
def foobar
"hello world"
end
end
Upvotes: 1
Views: 429
Reputation: 10122
This is a late reply, but I am trying to find a flexible way to do that too.
I found in Sinatra's source code (1.4.5) that creating an instance of the app with new!
allows testing the app's methods directly. Exert from a test setup with Test::Unit and Shoulda.
class AppTest < Test::Unit::TestCase
setup do
@app = App.new! # here is the point.
end
should 'say hello to the world' do
assert_equal "hello world", @app.foobar # or @app.send(:foobar) for private methods.
end
end
There are consequences. Using new!
does not create the usual Sinatra::Wrapper
that becomes the entry point to the middleware pipeline and the app in normal settings. So the new!
approach will work only if the tested methods are really "helpers" that do not rely on middleware functionalities (e.g. SSL).
Alternatively, a post on Rspec proposes an alternative solution. I used something similar in the past, but it requires more work that is not always the best choice. It had the advantage to offer broader coverage of code to test. The isolation of the app with new!
sounds good though, if we are taking about "unit" testing.
Note on @three's comment: A non-trivial app should separate API methods (usually in the app) from all helpers, etc. Helpers ending up in a separate file are cleaner, easier to maintain, and easier to test. But I definitely understand cases where a first version of an app would include a few helpers, with awareness that refactoring will be necessary. And even then having tests brings in some more confidence in the software itself, and in the future refactoring as well.
Upvotes: 1
Reputation: 814
It doesn't matter what you test - it is how :) => http://www.sinatrarb.com/testing.html
Upvotes: 0