Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing controller instance variables with Rack::Test and Sinatra

I have a Sinatra app that serves pages as read-only or editable depending on if the user is logged in.

The controller sets a variable @can_edit, that is used by the views to hide/show edit links. How can I test @can_edit's value in my tests? I have no idea how to get at the current instance of the controller under Rack::Test.

I use class_eval to stub the logged_in? method in the controller, but I'm having to resort to checking last_response.body for my edit links to see if @can_edit has been set or not.

How can I test the value of @can_edit directly?

like image 776
Brian Avatar asked Dec 18 '09 15:12

Brian


1 Answers

Unfortunately I don't think this is possible without modifying Rack::Test. When you make a request during application testing, Rack::Test does the following:

  1. adds the request to a list of recent requests
  2. creates a new instance of your application and invokes its call method
  3. adds your application's response to a list of recent responses

It's easy to access the last_request and last_response, but unfortunately no information is saved about the state of your application while it's running.

If you're interested in hacking together a Rack::Test patch to do this, start by looking at rack-test/lib/rack/mock_session.rb on line 30. This is where Rack::Test runs your application and receives the standard Rack app return values (status, headers, body). My guess is that you're going to have to modify your application as well, to collect and make accessible all of its instance variables.

In any case, it's best to test for results, not implementation details. If you want to make sure an edit link is not visible, test for the presence of the edit link by DOM id:

assert last_response.body.match(/<a href="..." id="...">/)
like image 175
Alex Reisner Avatar answered Oct 07 '22 10:10

Alex Reisner