tobogranyte
tobogranyte

Reputation: 939

How to reuse the same test multiple times in RSPEC

In one of my rspec test files, I need to run the following (otherwise identical) test in several different contexts:

describe "view the event with request" do
  before {
    click_link("Swimming lessons")
  }

  it { should have_content "Party Supplies"}

  describe "view the contribute form" do
    before {
      click_button("Party Supplies")
    }

    it {
      within("#bodyPopover") {
        should have_content('cupcakes')
        should have_content('napkins')
      }
    }


  end

end

I'd like to be able to put all this in a method (say view_the_event_and_contribute_form) and just use that method in several places in the rest of the test. Can that be accomplished? I tried defining a method which simply had that code, but it didn't recognize describe from within that method.

What's the best way to do this?

Upvotes: 4

Views: 3311

Answers (2)

infused
infused

Reputation: 24357

You can turn those tests into a shared_example:

shared_example "event with request" do
  before { click_link("Swimming lessons") }

  it { should have_content "Party Supplies"}

  describe "view the contribute form" do
    before { click_button("Party Supplies") }

    specify {
      within("#bodyPopover") {
        should have_content('cupcakes')
        should have_content('napkins')
      }
    }
  end
end

From other tests use it_behaves_like to run the shared examples:

describe 'Some other awesome tests' do
  it_behaves_like "event with request"
end

Upvotes: 4

Andy Waite
Andy Waite

Reputation: 11096

You almost had it. Just remove the describe, before and it blocks and move that code within a plain method.

Upvotes: 0

Related Questions