When I was adding tests for user authentication, I noticed an opportunity to DRY up the code a little by moving some duplicate tests into a shared example group. The tests expect to find different links in the header depending on the whether or not a user was signed in:
#partials_spec.rb
shared_examples "it has signed in header links" do
it { should have_link('Sign out', href: signout_path) }
it { should have_link('Subscriptions', href: user_path(user_id))}
it { should have_link('Account', href: edit_user_path(user_id))}
it { should_not have_link('Sign in', href: signin_path) }
end
shared_examples "it has signed out header links" do
it { should_not have_link('Sign out', href: signout_path) }
it { should have_link('Sign in', href: signin_path) }
end
By moving them into a separate file, the specs will be more adaptable when we need to change the links (and consequently, where they are referenced in the tests).
A Minor Oversight (and the easy fix)
Running “rspec” with the new shared example group in place caused RSpec to show this warning:
jimm$ rspec WARNING: Shared example group 'it has signed in header links' has been previously defined at: .../tosback3/spec/support/partials_spec.rb:1 ...and you are now defining it at: .../tosback3/spec/support/partials_spec.rb:1 The new definition will overwrite the original one. WARNING: Shared example group 'it has signed out header links' has been previously defined at: .../tosback3/spec/support/partials_spec.rb:8 ...and you are now defining it at: .../tosback3/spec/support/partials_spec.rb:8 The new definition will overwrite the original one.
I knew that spec_helper.rb was loading everything in the “support” directory, but I couldn’t explain why the file was being loaded twice when another file in the same directory was only being loaded once. After playing around with it, I finally realized that the name of the file is important too. By default, RSpec will load files that end in “_spec.rb”. The warnings disappeared when I changed the filename to “partials_shared.rb” and ran rspec again.