Ever wonder how you can write a cucumber test that would test how your web app responds to a different format, something like JSON or XML?
I was trying to do the following:

 Given I am logged in
 And there is the following feeds:
 | title | body | category |
 | first feed | something good | default |
 | second feed | even better | notice |
 | 3rd feed | something awesome | notice |

Scenario: Reading feeds via json
 When I go to the feeds page using json
 And I should see a json file
 And I should see 3 feeds in the json

Running this code I would get a “Can’t find mapping from “the feeds page using json” to a path.

Trying to figure out how I can do this, I tried to write a new step, like this:

When %r{^I go to the (w+) page using (w+)$} do |page, format|...

but this resulted in: Ambiguous match of “I go to the feeds page using json”

So, I posted the question on StackOverFlow and it seems everyone was thinking the same way I was.

I continued playing  with this idea and here is how I solved the problem:

Modifying the paths.rb file, I changed (Changes are in bold)

def path_to(page_name)
  # Split out format if page_name includes ' using '
  # Example: When I go to the accounts page using json
  page_name, format = page_name.split(' using ')
  case page_name
  when /the homes?page/
  when /the new account page/
    #pass format
    new_account_path(:format => format)

      page_name =~ /the (.*) page/
      path_components = $1.split(/s+/)
      # Also make sure to pass format to the 'guessed' path
      self.send(path_components.push('path').join('_').to_sym, :format => format)
    rescue Object => e
      raise "Can't find mapping from "#{page_name}" to a path.n" +
        "Now, go and add a mapping in #{__FILE__}"

This way I don’t have to modify anything else in my features and everything just works.

%d bloggers like this: