Skip to content

Instantly share code, notes, and snippets.

@SirRawlins
Last active August 12, 2022 19:42
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SirRawlins/8956101 to your computer and use it in GitHub Desktop.
Save SirRawlins/8956101 to your computer and use it in GitHub Desktop.
RSpec url matcher.
# Drop this into /spec/support/matchers
# Usage: result.should be_url
# Passes if result is a valid url, returns error "expected result to be url" if not.
# Matcher to see if a string is a URL or not.
RSpec::Matchers.define :be_url do |expected|
# The match method, returns true if valie, false if not.
match do |actual|
# Use the URI library to parse the string, returning false if this fails.
URI.parse(actual) rescue false
end
end
@nicolasrouanne
Copy link

Nice matcher.
You should probably avoid rescuing all exceptions though, it's generally bad practice.

You could do

match do |actual|
    # Use the URI library to parse the string, returning false if this fails.
    URI.parse(actual)
  rescue URI::InvalidURIError
    false
  end

@kdiogenes
Copy link

I'm using ruby 2.5.5 and it's returning a URI::Generic instead of raising an exception, so I implemented it like the following:

RSpec::Matchers.define :be_url do |expected|
  match do |actual|
    actual =~ URI::regexp
  end
end

@joshuapinter
Copy link

Am I the only one that prefers be_a_url instead of be_url?

Maybe it's because there is already be_a( Hash ), etc.

Thoughts?

@joshuapinter
Copy link

Also, ESLint was whining about the unused block variable, expected and URI:regexp being obsolet. It preferred the following:

RSpec::Matchers.define :be_a_url do
  match do |actual|
    actual =~ URI::DEFAULT_PARSER.make_regexp
  end
end

@ShamoX
Copy link

ShamoX commented Jul 8, 2021

Thanks for the matcher.

It would be nice if implemented in rspec project directly.

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