DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

[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

Top comments (0)