| 1 | # frozen_string_literal: true |
| 2 | |
| 3 | require "rails_helper" |
| 4 | |
| 5 | RSpec.describe User, ".find_or_create_from_smbcloud" do |
| 6 | it "creates a new user when the smbcloud_id is unseen and the email is free" do |
| 7 | expect do |
| 8 | user = User.find_or_create_from_smbcloud({ id: 100, email: "new@example.com" }) |
| 9 | expect(user.smbcloud_id).to eq(100) |
| 10 | expect(user.email).to eq("new@example.com") |
| 11 | end.to change(User, :count).by(1) |
| 12 | end |
| 13 | |
| 14 | it "returns the same record for a known smbcloud_id" do |
| 15 | existing = User.create!(smbcloud_id: 200, email: "known@example.com", username: "known") |
| 16 | expect do |
| 17 | user = User.find_or_create_from_smbcloud({ id: 200, email: "known@example.com" }) |
| 18 | expect(user.id).to eq(existing.id) |
| 19 | end.not_to change(User, :count) |
| 20 | end |
| 21 | |
| 22 | # The regression: smbCloud's auth_user id for an email can differ from the id |
| 23 | # stored on an older local record (e.g. a social login resolves to a different |
| 24 | # auth_user). Keying only on smbcloud_id would try to create a duplicate and |
| 25 | # fail on the unique email, wedging sign-in. |
| 26 | it "adopts an existing user by email and moves it to the new smbcloud_id" do |
| 27 | existing = User.create!(smbcloud_id: 18, email: "person@example.com", username: "person") |
| 28 | |
| 29 | user = nil |
| 30 | expect do |
| 31 | user = User.find_or_create_from_smbcloud({ id: 86, email: "person@example.com" }) |
| 32 | end.not_to change(User, :count) |
| 33 | |
| 34 | expect(user.id).to eq(existing.id) |
| 35 | expect(user.smbcloud_id).to eq(86) |
| 36 | expect(user.username).to eq("person") # username preserved |
| 37 | expect(existing.reload.smbcloud_id).to eq(86) |
| 38 | end |
| 39 | |
| 40 | it "matches the existing email case-insensitively" do |
| 41 | User.create!(smbcloud_id: 18, email: "mixed@example.com", username: "mixed") |
| 42 | user = User.find_or_create_from_smbcloud({ id: 99, email: "MIXED@example.com" }) |
| 43 | expect(user.smbcloud_id).to eq(99) |
| 44 | expect(User.where("lower(email) = ?", "mixed@example.com").count).to eq(1) |
| 45 | end |
| 46 | end |