Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RobertBrewitz/3253419 to your computer and use it in GitHub Desktop.
Save RobertBrewitz/3253419 to your computer and use it in GitHub Desktop.
Fill in valid data for a model with Capybara and FactoryGirl
When /^I fill in all required "(.*?)" fields$/ do |model|
klass = model.singularize.camelcase.constantize
# Build the class with valid attributes
# Requires valid factory
valid_model = FactoryGirl.build(model.singularize.to_sym)
# Remove ID field(s)
valid_model.attributes.delete("_id") if valid_model.attributes.include?("_id")
valid_model.attributes.delete("id") if valid_model.attributes.include?("id")
klass.fields.keys.each do |key|
field_name = (model + "_" + key)
begin
# Tries to find the field, rescued if not found
el = find_by_id(field_name)
# Tries to fill in data
if klass.validators_on(key).map(&:class).include?(Mongoid::Validations::PresenceValidator) != false
if el.tag_name == "select"
select(valid_model.attributes[key], from: field_name) # NOTE: case sensitive select
puts "select #{valid_model.attributes[key]} from #{field_name}."
end
if el.tag_name == "input" && el["type"] == "text"
if valid_model.fields[key].type == Integer
fill_in field_name, with: valid_model.attributes[key].to_i
puts "fill_in #{field_name} with #{valid_model.attributes[key]}."
end
if valid_model.fields[key].type == String
fill_in field_name, with: valid_model.attributes[key].to_s
puts "fill_in #{field_name} with #{valid_model.attributes[key]}."
end
end
end
rescue Capybara::ElementNotFound # Have to rescue to hinder irrelevant test failure
# if field wasn't found and is required by Mongoid::Validations::PresenceValidator print message, I would like to send a custom test failure message but dunnno how ;)
if klass.validators_on(key).map(&:class).include?(Mongoid::Validations::PresenceValidator) != false
puts field_name + " seems to be missing from the view!"
end
next
end
end
end
@RobertBrewitz
Copy link
Author

If someone can make this work nicer together with rspec expectation that would be awesome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment