Skip to content

Instantly share code, notes, and snippets.

@billguy
Last active December 15, 2016 19:56
Show Gist options
  • Save billguy/16b0dfa9e1f6900b6b5d6bbf79725ba7 to your computer and use it in GitHub Desktop.
Save billguy/16b0dfa9e1f6900b6b5d6bbf79725ba7 to your computer and use it in GitHub Desktop.
Populating all form fileds in Capybara from a Factory
module FormFieldsHelper
def populate_form_fields_from_factory(page, form_id, factory)
inputs = page.all(:css, "##{form_id} input, ##{form_id} textarea, ##{form_id} select")
inputs.reject{ |input| input[:id] == nil }.each do |input|
input_id = input[:id]
attribute_name = input_id.gsub("#{factory.class.name.underscore}_",'')
attribute = attribute_name.to_sym
attribute_value = factory.send(attribute)
if input.tag_name == 'select' # Select
input.find("option[value='#{attribute_value}']").select_option
elsif input.tag_name == 'input' && input['type'] == 'checkbox' # Checkbox
input.set(attribute_value)
elsif input.tag_name == 'input' && input['type'] == 'file' # File
attach_file(input_id, Rails.root + 'spec/support/test.pdf')
else # Text field
input.set(attribute_value)
end
end
end
end
RSpec.configure do |config|
config.include FormFieldsHelper, type: :feature
end
# Within some feature spec...
factory = FactoryGirl.build(:factory)
populate_form_fields_from_factory(page, 'form_id', factory) # Populates the form with values from the factory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment