Allow the expect change matcher to take regexps in to and from #62

Closed
wants to merge 2 commits into
from

2 participants

@davisre

It would often be handy to pass a regular expression to the expect change matcher's from and to methods, when you want to verify that some portion of a string is changed but don't care about the rest.

For example, I was recently writing specs for the 'slug' of an ActiveRecord, the string that gets appended to the record ID in the URL. (In "http://www.example.com/things/23-my-thing", the part generated by #to_param is "23-my-thing" where "my-thing" is the slug, based on some attribute.) In this example, I don't care what the ID is, but I want to make sure the slug is updated when something special happens:

expect {
    thing.rename "Estes Kefauver"
}.to change { thing.to_param }.from(/krazy-and-ignatz/).to(/estes-kefauver/)

This small commit makes it possible. Does it make sense to roll up?

Rob

@myronmarston myronmarston and 1 other commented on an outdated diff Feb 21, 2011
lib/rspec/matchers/change.rb
end
def matches_after?
- @given_to ? @to == @after : true
+ @given_to ? matches_pattern?(@to, @after) : true
+ end
+
+ def matches_pattern?(given, actual)
+ given.is_a?(Regexp) ? (given =~ actual) : (given == actual)
end
@myronmarston
RSpec member
myronmarston added a line comment Feb 21, 2011

I think it would be better to use the === operator, as that has known, flexible semantics.

@davisre
davisre added a line comment Feb 21, 2011

Meaning use === in all cases instead of == with most things and =~ with Regexp? I can see that, but I wouldn't want to break any existing specs, and changing == to === feels a little broad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@davisre

Actually, thinking about this a bit more, I like the === idea. In addition to the original regular expression example, it would allow something like

expect {
    thing.symbolize_name
}.to change { thing.name }.from(String).to(Symbol)

and other custom behaviors. I'll update the pull.

@davisre davisre Instead of special-casing Regexp, use ===
for all comparison of given vs actual, which allows not only
regular expressions but also classes and custom behavior.
ce44d09
@davisre

change matcher now accepts regexp in to/from

@dchelimsky dchelimsky closed this Mar 21, 2011
@kchien kchien pushed a commit to kchien/rspec-expectations that referenced this pull request Mar 7, 2014
@davisre davisre change matcher now accepts regexp in to/from
- Closes #62.
5774d5c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment