如何使用RSpec和Capybara验证完整的表格?

时间:2012-07-12 18:14:53

标签: ruby rspec capybara

我正在与RSpec和Capybara一起编写请求测试。我有一个哈希,将表单字段名称映射到期望值。

如何轻松检查每个表单字段是否具有预期值?

到目前为止,我正在这样做,但它很复杂且难以维护。在这种情况下,我也只考虑两种输入控件(选择框和其他选项):

expected_data = { 
  "address" => "Fake st 123",
  "city" => "Somewhere",
  "email" => "whoknows@example.com",
  "gender" => "Male",
  "state" => "FL",
}

select_boxes = ["gender", "state"]
# check for the select boxes
expected_data.select {|k,v| select_boxes.include?(k)}.each do |name, expected_value|
  page.has_select?(name, :selected_value => expected_value).should == true
end 
# check for the input fields
expected_data.reject {|k,v| select_boxes.include?(k)}.values.each do |expected_value|
  page.should have_css("input[value=\"#{expected_value}\"]")
end 

在一行中是否有宝石或其他东西?

1 个答案:

答案 0 :(得分:5)

我发现以下内容更易于维护:

describe "form" do
  subject {page}

  before { visit "/path/to/form" }

  it { should have_field("address", :with => "Fake st 123") }
  it { should have_select("gender", :selected => "Male") }
  # And so on ...
end