Skip to content

Instantly share code, notes, and snippets.

@ekampp
Last active December 15, 2015 18:49
Show Gist options
  • Save ekampp/5306603 to your computer and use it in GitHub Desktop.
Save ekampp/5306603 to your computer and use it in GitHub Desktop.
Filling out a form, simply in capybara. I always felt that doing the whole "within.. fill_in..." felt a bit tiresome for standard forms. So I extracted it into an includable context snippet.
# This will fill out the form defined in the `form` hash, and it will fill the
# form elements with the data from the `atrs` hash. So you need to define both
# before incuding this context.
#
# The smallest, possible example:
#
# include_context :fill_and_submit_form do
# let(:form){ {id: "new_user_form" } }
# let(:atrs) { {name: "Weeble & Bob"} }
# end
#
# Another example, where the id of the submit button is something other than
# commit.
#
# include_context :fill_and_submit_form do
# let(:form){ {id: "new_user_form", commit: "submit" } }
# let(:atrs) { {name: "Weeble & Bob"} }
# end
#
# Lastly an example where the name of the elements in the form is something
# other than can be inferred from the id.
#
# include_context :fill_and_submit_form do
# let(:form){ {id: "new_user_form", name: "person" } }
# let(:atrs) { {name: "Weeble & Bob"} }
# end
#
shared_context :fill_and_submit_form do
before do
within form[:id] do
atrs.compact.each do |field, value|
fill_in "#{(form[:name] || form[:id].split('_')[1])}_#{field}", with: value
end
click_button form[:commit] || "commit"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment