Testing Rails redirect_back with RSpec
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
Rails has a handy redirect method called
redirect_back(fallback_location:) which replaces the old
redirect_to :back syntax. It's improved now because it gracefully handles the case where there is no referrer and allows you to indicate where the visitor should be sent to. The only issue is there's no testing support for it out of the box.
You can of course just test that a visitor is redirected to the fallback location, that's fine. But if it's important to your app that the visitor is redirected back to where they came from you'll need to make some changes.
First, make a helper module in
spec/support/redirect_back.rb which simply defines the
Really simple - just sets the
HTTP_REFERER (typo intended) which Rails will then attempt to use as the "back" location. Then, simply include the
RedirectBack helper module with RSpec so you can use the method in your specs.
Then you can call the
from method in your tests whenever you want to test the
redirect_back functionality. Here's an example test which shows how we come "from" the about page and then expect to get redirected back there should the request be handled successfully.