master
 1require "rails_helper"
 2
 3describe UserSession do
 4  subject { build(:user_session) }
 5
 6  describe "#revoke!" do
 7    it "records the time the session was revoked" do
 8      subject.revoke!
 9      expect(subject.revoked_at).to_not be_nil
10    end
11  end
12
13  describe "#access" do
14    let(:request) { double(ip: '192.168.1.1', user_agent: 'blah') }
15    let(:location) { build(:location) }
16    let(:because) {  subject.access(request) }
17
18    before :each do
19      allow(Location).to receive(:build_from_ip).with('192.168.1.1').and_return(location)
20      because
21    end
22
23    it "records the time the session was accessed" do
24      expect(subject.accessed_at).to_not be_nil
25    end
26
27    it "records the ip address of the request" do
28      expect(subject.ip).to eql(request.ip)
29    end
30
31    it "records the user agent of the request" do
32      expect(subject.user_agent).to eql(request.user_agent)
33    end
34
35    it 'records a location for the session' do
36      expect(subject.location).to_not be_nil
37    end
38
39    it "returns a hash to store in the cookie" do
40      expect(because).to eql(subject.key)
41    end
42  end
43
44  describe ".active" do
45    let!(:active_session) { create(:user_session, accessed_at: Time.now) }
46    let!(:expired_session) { create(:user_session, accessed_at: 15.days.ago) }
47    let!(:revoked_session) { create(:user_session, accessed_at: 1.day.ago, revoked_at: Time.now) }
48
49    it "returns active sessions" do
50      expect(UserSession.active).to include(active_session)
51    end
52
53    it "excludes expired sessions" do
54      expect(UserSession.active).to_not include(expired_session)
55    end
56
57    it "excludes revoked sessions" do
58      expect(UserSession.active).to_not include(revoked_session)
59    end
60  end
61
62  describe ".authenticate" do
63    let!(:active_session) { create(:user_session, accessed_at: Time.now) }
64
65    it "returns the session if the key is active" do
66      expect(UserSession.authenticate(active_session.key)).to eql(active_session)
67    end
68
69    it "return nil if the key is not active" do
70      expect(UserSession.authenticate('blah')).to be_nil
71    end
72  end
73
74  it "creates one key" do
75    session = UserSession.create(user: create(:user))
76    expect(session.key).to_not be_nil
77    key = session.key
78    session.accessed_at = Time.now
79    session.save!
80    expect(session.key).to eql(key)
81  end
82end