nowk
3/21/2012 - 11:56 PM

Email matchers

Email matchers

RSpec::Matchers.define :be_from do |expected|
  match do |actual|
    actual.from_addrs.include?(expected)
  end

  failure_message_for_should do |actual|
    %{expected to be from #{expected} but was from #{actual.from_addrs.join(', ')}}
  end

  failure_message_for_should_not do |actual|
    %{expected to not be from "#{expected}"}
  end

  description do
    # //
  end
end

# => email.should be_from "someone@domain.com"

RSpec::Matchers.define :have_the_subject do |expected|
  match do |actual|
    actual.subject == expected
  end

  failure_message_for_should do |actual|
    %{expected the subject to be "#{expected}" but was "#{actual.subject}"}
  end

  failure_message_for_should_not do |actual|
    %{expected the subject not to be "#{expected}"}
  end
end

# => email.should have_the_subject "This is just a subject"

RSpec::Matchers.define :contain_in_the_message do |expected|
  match do |actual|
    actual.encoded =~ /#{expected}/
  end
end

# => email.should contain_in_the_message "This should be in the message"

RSpec::Matchers.define :have_an_html_version do
  match do |actual|
    actual.encoded =~ /Content-Type: text\/html;/
  end

  failure_message_for_should do |actual|
    %{expected the email to have an text/html version}
  end

  failure_message_for_should_not do |actual|
    %{expected the email to not have an text/html version}
  end
end

# => email.should have_an_html_version

RSpec::Matchers.define :have_a_text_version do
  match do |actual|
    actual.encoded =~ /Content-Type: text\/plain;/
  end

  failure_message_for_should do |actual|
    %{expected the email to have a text/plain version}
  end

  failure_message_for_should_not do |actual|
    %{expected the email to not have a text/plain version}
  end
end

# => email.should have_a_text_version