Today I Learned

hashrocket A Hashrocket project

Mocking Requests With Partial URIs Using Regex

Generally when mocking out requests with the webmock gem, we specify full request URIs like so:

stub_request(:post, 'http://localhost:4000/api/posts')

We may not want to specify the entire URI though. For instance, the host may change or be configurable. The stub_request method allows us to use regex.

stub_request(:post, %r|/api/posts|)

Using the %r regex literal syntax, we are able to avoid escaping all of the / characters in our URI.

h/t Brian Dunn

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.