In my ApplicationController, I expose a variable that can be shared by all controllers:
before_filter :expose_group
protected
# Much simplified
def expose_group
@user_group = LearningGroup.find_by_uid(cookies[:user_group])
end
I'm testing my controllers using RSpec, and for some of these tests, I need to be able to set the @user_group to a known value before they are run. How can I set this variable when testing a subclass of ApplicationController?
Note: I need a way to set @user_group for the test. Controlling the return value of expose_group using a stub doesn't help as @user_group will still be nil.
I would scrap the instance variable altogether and use helpers instead. Start with something like a
GroupsHelperinapp/helpers/groups_helper.rb.Then
includeit inApplicationController.Now, in
spec/supportdefine a helper for your test.A test could look something like:
When you run your test,
user_groupwill return the value determined by the value you already assigned to the cookie object.This also has the benefit of just calling
join_grouprather than stubbingLearningGroupall over the place in multiple tests.