DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

2

[Capybara] like shared_examples

🤔 Situation

It's difficult to read to and not_to. This makes human mistakes.

scenario 'Each panel should be isolated open/close ' do
  visit hoge_path(hoge_params)
  within('div.section-fugas') do
    expect(find('div.section-fuga:nth-child(1)')).to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(2)')).to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(3)')).not_to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(4)')).not_to have_selector('div.section-fuga-body')
    find('div.section-fuga:nth-child(1)').find('a.section-fuga-a').click
    expect(find('div.section-fuga:nth-child(1)')).not_to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(2)')).to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(3)')).not_to have_selector('div.section-fuga-body')
    expect(find('div.section-fuga:nth-child(4)')).not_to have_selector('div.section-fuga-body')
  end
end

👍 Solution

  • PORO, we have the def.
  • Plus, we get more flexibility by send(method, args).
  • Then, we can concentrate to judge the true/false.
def visibility_test(visibility_bools)
  expect(find('div.section-fuga:nth-child(1)')).send(visibility_bools[0] ? :to : :not_to, have_selector('div.section-fuga-body'))
  expect(find('div.section-fuga:nth-child(2)')).send(visibility_bools[1] ? :to : :not_to, have_selector('div.section-fuga-body'))
  expect(find('div.section-fuga:nth-child(3)')).send(visibility_bools[2] ? :to : :not_to, have_selector('div.section-fuga-body'))
  expect(find('div.section-fuga:nth-child(4)')).send(visibility_bools[3] ? :to : :not_to, have_selector('div.section-fuga-body'))
end

scenario 'Each panel should be isolated open/close ' do
  visit hoge_path(hoge_params)
  within('div.section-fugas') do
    visibility_test([true,true,false,false])
    find('div.section-fuga:nth-child(1)').find('a.section-fuga-a').click
    visibility_test([false,true,false,false])
  end
end

🔗 Parent Note

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →