Search code examples
rubyregexunit-testingrspecrspec-rails

How to use RSpec regex argument matching on certain types of arguments


RSpec provides argument regex matchers like the following example:

mock_smtp.should_receive(:send_message).with(anything, anything, /@just-testing.com/)

which is nice, and allows me to catch arguments that match the regex, which works fine for the example (matching a string, ending in '@just-testing.com').

My problem is that I can't get this to work for arguments of this type:

    msgstr = <<END_OF_MESSAGE
From: me <#{from_email}>
To: #{to_name} <#{to_email}>
Subject: #{subject}
MIME-Version: 1.0
Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">...</html>
END_OF_MESSAGE

Nothing within the msgstr variable is capturable with the regex.

How can I test for values within the msgstr variable?


Solution

  • Not sure what problem you're having, but the following works fine:

    from_email = to_email = subject = to_name = "[email protected]"
    
    msgstr = <<END_OF_MESSAGE
    From: me <#{from_email}>
    To: #{to_name} <#{to_email}>
    Subject: #{subject}
    MIME-Version: 1.0
    Content-type: text/html
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">...</html>
    END_OF_MESSAGE
    
    def foo(arg)
    end
    
    describe "" do
      it "" do
        expect(self).to receive(:foo).with(/@just-testing.com/)
        foo(msgstr)
      end
    end