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

时间:2016-06-15 15:37:15

标签: ruby rubygems cucumber capybara

我是黄瓜新手,拥有最简单的黄瓜/红宝石/水豚/硒驱虫剂。

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

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可能缺少信息,或者我只是没有使用正确的语法? 我已经在网上和在这个网站上搜索了几天,任何帮助将不胜感激! 感谢您的时间。 Melie

1 个答案:

答案 0 :(得分:2)

使用场景轮廓时,表值将传递给步骤定义。它不是通过的表。步骤:

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