alf
alf

Reputation: 18530

How to validate a complete form with RSpec and Capybara?

I'm writing a request test with RSpec and Capybara. I have a hash that maps form field names to expected values.

How can I check easily that each form field has the expected value?

So far, I'm doing this, but it's complex and unmaintainable. I'm also considering only two kind of input controls in this case (select boxes and the rest):

expected_data = { 
  "address" => "Fake st 123",
  "city" => "Somewhere",
  "email" => "[email protected]",
  "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 

Is there a gem or something to do this in one line?

Upvotes: 0

Views: 2968

Answers (1)

Tanzeeb Khalili
Tanzeeb Khalili

Reputation: 7344

I find the following far more maintainable:

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

Upvotes: 5

Related Questions