Question

I need test sidebars on every site page. I define user method test_all_sidebars and fill in

def test_all_sidebars
    test_header
    test_contacts
    test_news
    test_footer
end

then I need test for one page 2 sidebars will not show. Example:

describe "Home page" do
    before { visit root_path }

    test_all_sidebars
end
describe "Contact page" do
    before { visit contact_path }

    test_header
    test_footer
    test_news(false)
    test_contact(false)
end

I try to define test_news and test_contact with option like this

def test_contacts(flag: true)
    describe "sidebar with contacts" do
        it { (:flag ? should : should_not) have_content('phone: ') }
    end

but it doesnt work. I have unexpected tIDENTIFIER, expecting '}'

I tried use let

def test_contacts(flag: true)
    if :flag then
        let(:sh) { should }
    else
        let(:sh) { should_not }
    end
    it { sh have_content('phone: ') }
end

but this still doesnt work.

My question: HOW? How I can use should/should_not in same method using input data condition?

Was it helpful?

Solution

def test_contacts(flag: true)
  describe "sidebar with contacts" do
    it { (:flag ? should : should_not) have_content('phone: ') }
  end
end

So much is wrong with this code:

  1. :flag is always truthy, since it is a symbol. If you want to check if the value passed it true you should use flag (the variable), not :flag (the symbol)
  2. should and should_not are methods, so actually you need to call either should(have_content('phone: ') or should_not(have_content('phone: ') - you can't separate the method call from the variables you send it.

So, inside your describe your code should look like:

it { flag ? should(have_content('phone: ')) : should_not(have_content('phone: ') }

Beside this, I've never seen this kind of pattern for writing rspec test cases, and I'm pretty sure you are better off using better idioms like shared_examples_for

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top