As you can guess when reading the title, I am using Rspec to test my RoR code. In my tests I want to verify that I am on a certain page after some action and also verify that certain elements are present on that page. I use the following code for this:
# Show page title
it { should have_selector('title', text: "Button text") }
# Show form fields
it { should have_selector('input', id: "user_email") }
it { should have_selector('input', id: "user_password") }
it { should have_selector('input', id: "user_password_confirmation") }
it { should have_selector('input', value: "Schrijf me in") }
But in another test I also want to verify being on the same page. I can use the above code again but that doesn't feel right.
I want to use an Rspec custom matcher to do this. But the only examples I can find require an argument to pass to the matcher or can only verify one selector. How can I write a custom matcher to do this?
If your tests are the same, what you want is shared_examples
.
shared_examples 'on user home page' do
# Show page title
it { should have_selector('title', text: "Button text") }
# Show form fields
it { should have_selector('input', id: "user_email") }
it { should have_selector('input', id: "user_password") }
it { should have_selector('input', id: "user_password_confirmation") }
it { should have_selector('input', value: "Schrijf me in") }
end
# Spec File #1
describe 'Test one' do
it_behaves_like 'on user home page'
end
# Spec File #2
describe 'Test two' do
it_behaves_like 'on user home page'
end