From 9402699a4209a67bf949a2c72f4344e8585bf7dd Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Mon, 27 Apr 2020 15:34:52 +0200 Subject: [PATCH] DX: - Add `password_plain` method to all `User` records created by FactoryBot to access the plain password for reuse to avoid variable spaming. - Enable Capybara system test meta attribute `:authenticate` to handle a user as lambda return value which will be used for authentication instead of default `master@example.com`. --- spec/factories/user.rb | 6 ++++++ spec/support/capybara/authenticated.rb | 26 ++++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/spec/factories/user.rb b/spec/factories/user.rb index 8375a57fc..391ee0703 100644 --- a/spec/factories/user.rb +++ b/spec/factories/user.rb @@ -25,5 +25,11 @@ FactoryBot.define do factory :admin_user, aliases: %i[admin] do roles { Role.where(name: %w[Admin Agent]) } end + + # make given password accessible for e.g. authentication logic + before(:create) do |user| + password_plain = user.password + user.define_singleton_method(:password_plain, -> { password_plain }) + end end end diff --git a/spec/support/capybara/authenticated.rb b/spec/support/capybara/authenticated.rb index 394280e2b..0b036d96e 100644 --- a/spec/support/capybara/authenticated.rb +++ b/spec/support/capybara/authenticated.rb @@ -14,12 +14,26 @@ RSpec.configure do |config| next if !example.metadata.fetch(:set_up, true) # check if authentication should be performed - next if example.metadata.fetch(:authenticated, true).blank? + authenticated = example.metadata.fetch(:authenticated, true) + next if authenticated.blank? - # authenticate - login( - username: 'master@example.com', - password: 'test', - ) + if authenticated.is_a?(Proc) + user = instance_exec(&authenticated) + password = user.password_plain + + raise "Can't authenticate user that has no password set" if password.blank? + + credentials = { + username: user.email, + password: password, + } + else + credentials = { + username: 'master@example.com', + password: 'test', + } + end + + login(credentials) end end