1

I've created a module so I can quickly create users, sign in as users, delete users and sign out users. Here is a simplified example:

module UserAuth
    def sign_in(user)
        cookies.permanent[:remember_token] = 'asda'
    end
end

However, if I run this spec:

describe 'UserAuth' do
    include UserAuth

    context 'signed up' do
        let(:user_1) { FactoryGirl.build(:user) }
        before { sign_up user_1 }

        contex 'signed in' do
            before { sign_in user_1 }

            it {}

        end
    end
end

I get this error:

   undefined method `permanent' for #<Rack::Test::CookieJar:#>

What I find weird about this is that cookies object is available, but this permanent method isn't for some reason. Can I resolve this issue by simply including another module in the UserAuth module? If so, what is the name of this module?

Starkers
  • 10,273
  • 21
  • 95
  • 158

2 Answers2

0

It seems the RackTest CookieJar and Cookie classes do not offer these methods for testing within its MockSession. What I did is mock the methods setting cookies this way, and rather return my own result, or use RackTest's cookie methods to set cookies.

Note: In this example I'm mocking a method that is setting a cookie through a concern.

before :each do
  allow(MyConcern).to receive(cookie_method) { create(:cookie, :test) }
end

it 'tests cookie' do
  cookie_method

  expect {
    put item_path({test_id: 2})
  }.to change(Item, :test_id)

  expect(response.cookies[:cookie_id]).to eq 'test'
end 

Here's another SO article going over this same issue, and showing implementations.

Another option is to use RackTest's CookieJar methods instead, which offer the basics of cookie creation, as well as few other options.

it 'has a cookie' do
  cookies[:remember_token] = 'my test'
  post items_path
  expect(response.cookies[:remember_token]).to eq 'my test'
end

You can check out the methods in the RackTest's CookieJar/Cookie Source which is very straight-forward, but not so much for the API docs.

I hope that helps someone, and I also hope someone else comes along with a much better solution!

DBrown
  • 5,111
  • 2
  • 23
  • 24
-2

I suggest you follow the method for testing this defined in the Rails Tutorial, as shown in http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#code-sign_in_helper. The CookieJar object in Rack::Test is not the same as the one used by Rails in ActionDispatch::Cookies.

See related RailsTutorial: NoMethodError 'permanent' Rake::Test::CookieJar

Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106