Cucumber generic method for handling Webrat visit method
Saturday, February 7th, 2009Here’s a tip for creating a generic Cucumber step, handling the Webrat visit method.
Imagine you have many Cucumber scenarios, and you have many steps like these:
Given I am on the new task page
Given I am on the new project page
Given I am on the home page
This way you’d have to create mapping between these strings above, to real paths inside the application. You could use the method ‘path_to’, which is already provided with Cucumber, inside features/support/paths.rb. That could lead to something like this:
# features/support/paths.rb
def path_to(page_name)
case page_name
when /new task/i
new_task_path
when /tasks/i
tasks_path
when /new user/i
new_user_path
when /users/i
users_path
when /home/i
root_path
# and so forth...
else
raise "Can't find mapping from \"#{page_name}\" to a path."
end
end
Or you could use something more generic and more maintanable.
So, let’s take advantage of the path helpers already provided by Rails such as new_task_page, tasks_path, home_path, and do this instead:
Given I am on the new_task page
Given I am on the new_project page
Given I am on the home page
And add this to your create_task_steps.rb:
# features/step_definitions/create_task_steps.rb
Given /^I am on the (.+) page$/ do |page_name|
eval("visit #{page_name}_path")
end
This way Webrat will visit the path: new_page_path, and you won’t have to maintain the paths.rb file.