Last active
August 23, 2021 01:57
-
-
Save nruth/1264245 to your computer and use it in GitHub Desktop.
Shared Capybara (or model setup) helpers for RSpec and Cucumber
This file contains hidden or 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
# Let's assume you're driving Capybara in both RSpec request specs & Cucumber, | |
# for example you're using Cucumber as a design/documentation tool, and RSpec | |
# for the more boring integration tests. | |
# You don't want to duplicate your click-this-click-that helpers to e.g. | |
# log_in(username, password). | |
# You may also have model state setup code which can be shared/reused. | |
# Where can it go? How can it be loaded? I've been using the following approach: | |
# | |
# test_helper_lib/app_specific | |
# test_helper_lib/generic | |
# | |
# For example: | |
# test_helper_lib/generic/rails_dom_id_helper.rb | |
module RailsDomIdHelper | |
def rails_dom_id_for(model) | |
ActionController::RecordIdentifier.dom_id(model) | |
end | |
def rails_dom_id_selector(model) | |
"##{rails_dom_id_for(model)}" | |
end | |
end | |
RSpec.configure do |config| | |
config.include RailsDomIdHelper, :type => :request | |
end | |
World(RailsDomIdHelper) if respond_to?(:World) #cucumber | |
# and for an app-specific example: | |
module CapybaraAuthenticationHelpers | |
def log_out_admin | |
visit '/admin' | |
click_on('Sign out') | |
end | |
def admin_log_in_as(email, password) | |
visit '/admin' | |
fill_in("admin_email", :with => email) | |
fill_in("admin_password", :with => password) | |
click_button("admin_submit") | |
end | |
end | |
if respond_to?(:World) #cucumber | |
World(CapybaraAuthenticationHelpers) | |
else | |
RSpec.configure do |config| | |
config.include CapybaraAuthenticationHelpers, :type => :request | |
end | |
end | |
# And when including model setup methods you can drop the :type => :request, which defaults to :all. | |
# It works pretty well, and if you're really paranoid, or have complex state, | |
# you can even test your test setup code in 1 place. | |
# To have RSpec and Cucumber actually load the directory, you can add the following to a .rb file | |
# of your choice in spec/support and features/support | |
Dir[ | |
File.expand_path( | |
Rails.root.join 'test_helper_lib', '**', '*.rb' | |
) | |
].each {|f| require f} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are looking for a more complete solution for encapsulation, check out Capybara Test Helpers.
It allows to organize code to avoid repetition, while keeping it modular and maintainable.