summaryrefslogtreecommitdiff
path: root/spec/support/helpers/email_helpers.rb
blob: a7175491fa0767bf2ca37fdbda43f664972ffae2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module EmailHelpers
  def sent_to_user(user, recipients: email_recipients)
    recipients.count { |to| to == user.notification_email }
  end

  def reset_delivered_emails!
    ActionMailer::Base.deliveries.clear
  end

  def should_only_email(*users, kind: :to)
    recipients = email_recipients(kind: kind)

    users.each { |user| should_email(user, recipients: recipients) }

    expect(recipients.count).to eq(users.count)
  end

  def should_email(user, times: 1, recipients: email_recipients)
    amount = sent_to_user(user, recipients: recipients)
    failed_message = lambda { "User #{user.username} (#{user.id}): email test failed (expected #{times}, got #{amount})" }
    expect(amount).to eq(times), failed_message
  end

  def should_not_email(user, recipients: email_recipients)
    should_email(user, times: 0, recipients: recipients)
  end

  def should_not_email_anyone
    expect(ActionMailer::Base.deliveries).to be_empty
  end

  def email_recipients(kind: :to)
    ActionMailer::Base.deliveries.flat_map(&kind)
  end

  def find_email_for(user)
    ActionMailer::Base.deliveries.find { |d| d.to.include?(user.notification_email) }
  end

  def have_referable_subject(referable, include_project: true, include_group: false, reply: false)
    context = []

    context << referable.project.name if include_project && referable.project
    context << referable.project.group.name if include_group && referable.project.group

    prefix =
      if context.any?
        context.join(' | ') + ' | '
      else
        ''
      end

    prefix = "Re: #{prefix}" if reply

    suffix = "#{referable.title} (#{referable.to_reference})"

    have_subject [prefix, suffix].compact.join
  end
end