Created
August 4, 2012 01:43
-
-
Save RobertBrewitz/3253419 to your computer and use it in GitHub Desktop.
Fill in valid data for a model with Capybara and FactoryGirl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If someone can make this work nicer together with rspec expectation that would be awesome :)