[rspec-users] How to access local variable(s) of controller methods called via RSpec in Rails 3
dchelimsky at gmail.com
Thu Nov 17 15:22:30 EST 2011
On Nov 17, 2011, at 10:52 AM, Mohnish G j wrote:
> I'm testing for action caching via RSpec. Currently the method that is
> cached is in a controller. I'm able to call this method using
> `subject.send(:method_name)` Thanks to this
> I want to test a scenario to check if action caching is perfectly
> working. My test case goes something like this:-
> **Step 1** : Call the action which is cached. This action has an
> instance variable which stores queried results of user specific stats
> like number of users belonging to each of the areas out of a number of
> areas within a city. I need to fetch the initial set of results some how
> from the controller to my spec file.( **The question is how do I do that
> **Step 2**: Update an area for a single user. This would change the
> overall stats wrt this area(if it already exists) or would add a new
> area if its completely unique.
> **Step 3**: Recall the cached action, and check If I am still able to
> end up with the old results, not the latest changes as of what was done
> in step 2; in terms area stats for the users. Now to do this, I need to
> use the instance variable result as in Step 1, with an instance variable
> result I obtain after recalling the cached action this very Step.
> **Step 4**: Finally , comparing both results, they should be same. This
> would pass my test case.
> The **BIG** Question again, how do I access the local variable(s) of a
> controller method in my spec file?
You don't need to, so why would you want to?
Here's the strategy I use to spec caching, and I think this is pretty common.
1. In a request spec (or integration, if you prefer that naming), write an end to end example that specifies that you repeatedly get the same result. This doesn't say anything about caching, just that the same result comes back twice. This should have no stubbing or mocking. It will be slow, but there's only one of these.
2. In a controller spec, set a message expectation on a model that the query is only requested once, and invoke the controller action twice. e.g.
That's it! No need to interrogate internals. No need to actually access data. The only thing being mocked is on the surface of the object.
Now you probably want to specify how/when the cache expires as well, but that's a different matter. This only covers the caching itself.
More information about the rspec-users