Cucumber:如何在 Ruby Capybara 中编写定义步骤

Cucumber: How to write definition steps in Ruby Capybara

我是 Cucumber 的新手,并且拥有最简单的 cucumber/ruby/capybara/selenium 驱动程序设置。

我有一个场景大纲,例如:

Feature: Country of user is displayed
Scenario Outline: CountryCode of User is displayed based on his Country selected.
Given the user is on the test page
When I select my "<Country>" 
And the testpage is loaded
Then the "<CountryCode>" is displayed

Examples:
 | Country       | CountryCode |
 | Canada        | CA          |
 | United States | US          |

步骤定义:

 Given(/^the user is on the test page$/) do
 visit 'http://....'
end

When(/^I select my "([^"]*)"$/) do |table|
 select([Country], :from => 'id-of-dropdown')
 click_on('Submit')
end

When(/^the testpage is loaded$/) do
 pending # Write code here that turns the phrase above into concrete actions
end

Then(/^the "([^"]*)" from UserSetLocation is displayed$/) do |arg1|
 pending # Write code here that turns the phrase above into concrete actions
end

我的env.rb文件:

require 'rubygems'
require 'capybara'
require 'capybara/dsl'
require 'rspec'

Capybara.run_server = false
#Set default driver as Selenium
Capybara.default_driver = :selenium
#Set default driver as webkit (browserless)
#Capybara.javascript_driver = :webkit
#Set default selector as css
Capybara.default_selector = :css

#Syncronization related settings
module Helpers
 def without_resynchronize
  page.driver.options[:resynchronize] = false
  yield
  page.driver.options[:resynchronize] = true
 end
end
World(Capybara::DSL, Helpers)

我遇到的问题是从数据表国家列中提取值的正确语法是什么:

When(/^I enter my "([^"]*)"$/) do |table|
   select([Country], :from => 'id-of-dropdown')

以下工作,但我不想为每个国家/地区编写相同的步骤,该数据表可能包含数十个国家/地区。

select("Canada", :from => 'id-of-dropdown')

我意识到我的 env.rb 可能缺少信息,或者我只是没有使用正确的语法? 我已经在网上和这个网站上搜索了好几天,如果有任何帮助,我们将不胜感激! 感谢您的时间。 梅莉

使用场景大纲时,table 值会传递给步骤定义。传递的不是table。步骤:

When I select my "<Country>" 

在概念上等同于:

When I select my "Canada" 

When I select my "United States" 

在步骤定义中,table是引号之间的捕获值。你可以看到它只是一个 String.

When(/^I select my "([^"]*)"$/) do |table|
  p table.class
  #=> String

  p table
  #=> "Canada" or "United States"
end

您可以将此值直接传递给 select 方法。您可能想重命名变量以反映其值:

When(/^I select my "([^"]*)"$/) do |country|
  select(country, :from => 'id-of-dropdown')
  click_on('Submit')
end