My stub_current_user RSpec Helper

Jun 27th, 2008 — 3:36 PM

The other day I came up with a really useful spec helper for stubbing out the ubiquitous current_user all over my specs and thought I’d share it with the world. It might end up as part of Skinny Spec but might be a little too tied in a specific authentication pattern. Dunno. Here it is anyhow:

def stub_current_user(stubs = {})
  returning stub_model(User, stubs) do |user|
    object = case self
      when Spec::Rails::Example::ViewExampleGroup : template
      when Spec::Rails::Example::HelperExampleGroup : helper
      when Spec::Rails::Example::ControllerExampleGroup
        User.stub!(:find).with(user.id).and_return(user)
        # Because params values are actually strings
        User.stub!(:find).with(user.id.to_s).and_return(user)
        controller
    end
    object.stub!(:current_user).and_return(user)
  end
end

It uses the new stub_model method available in RSpec versions greater than 1.1.4 instead of mock_model. You can totally just replace that call with one to mock_model but I encourage you to try it out because it allows you a lot more flexibility in your view specs. You can read a little more about it in David Chelimsky’s post about RSpec 1.1.4. Love that new hash_including action as well. Been looking for something like that for a long time.

Filed under: rails, rspec

Leave a Comment

Lucky Sneaks is designed and managed by Lucky Sneaks
All content © Lucky Sneaks 2008
Lucky Sneaks is Lucky Sneaks