02 July 2014

Here’s another tip about RSpec/Capybara testing. So, for example, when you want to test a current path of a page you were redirected to or something, normally you will write something like this:

expect(current_path).to eq("/sample/route")

or

expect(current_path).to eq(sample_route_path)

if you prefer to use named routes.

But it’s not going to work when you want to test a path with given params. For example:

visit("/sample/route?page=3")
  puts "current_url = #{current_url.inspect}"
  puts "current_path = #{current_path.inspect}"

will give you outputs:

current_url = "http://domain.subdomain/sample/route?page=3"
  current_path = "/sample/route"

And neither full url nor path without params is what we want here. My solution is to add this method to a module (existed or newly created) inside rspec/support folder of a rails app:

module PathCapybaraModule

    def current_path_with_params
      URI.parse(current_url).request_uri
    end

  end

To use it you just need to include that module in your spec_helper.rb, like this:

RSpec.configure do |config|
    config.include PathCapybaraModule
  end

So, now if you try:

visit("/sample/route?page=3")
  puts "current_path_with_params = #{current_path_with_params.inspect}"
  puts expect(current_path_with_params).to eq("/sample/route?page=3")
  puts expect(current_path_with_params).to eq(sample_route_path(:page => 3))

it will give you:

current_path_with_params = "/sample/route?page=3"
  true
  true

As you can see it works well with both a string-given path and a named route. Enjoy!