Tags

,

When making a rspec test for controller(controller test), we might encountered that a particular controller need to be authenticated. So, in order to solve that we need to create a signed_cookie helper.
Create a helper file(helpers.rb) inside the spec/support/ folder and then copy the code below.

##Create a signed_cookie method:
def signed_cookies(name, opts={})
  verifier = ActiveSupport::MessageVerifier.new(request.env["action_dispatch.secret_token".freeze])
  if opts[:value]
    @request.cookies[name] = verifier.generate(opts[:value])
  else
    verifier.verify(cookies[name])
  end
end 

In your rspec file(add_user_spec.rb), we can use the signed_cookie method.

describe "POST #add_user" do
it "add user to admin groups" do
  user = FactoryGirl.create(:user, :id=>1, :username=>"tzjack@bing.com")
  FactoryGirl.create(:groups_user, :group_id=>2, :user_id=>user.id)
  signed_cookies(:user_id, :value => user.id)
  . . .
end

Also, there is an alternative way to bypass the checking from is_logged_in method, we can use controller.class.skip_before_filter

describe Admin::GroupsController do
  before(:each) do
    controller.class.skip_before_filter :is_logged_in
  end
end
Advertisements