Jonathan Tuzman
Jonathan Tuzman

Reputation: 13272

Run a spec from another spec?

I have a spec like this:

it "creates a new deal"
  # visit 'new' page
  # use capybara to fill out lots of form fields and hit submit
  # test all the values of the created Deal object
end

I want my next spec to test that it "redirects to the show page for the newly created deal", and I'd love if it could just pick up where the last spec left off and test the current_path.

Is there a way to say "run this other spec and then add these expectations to it"? Rather than pasting in all the directions from the other spec.

Upvotes: 0

Views: 405

Answers (3)

max
max

Reputation: 102194

I want my next spec to test that it "redirects to the show page for the newly created deal", and I'd love if it could just pick up where the last spec left off and test the current_path.

You can use shared contexts to share setup steps, let blocks etc.

RSpec.shared_context "authenticated" do
  let(:user){ create(:user) }
  before do
    login_as(user, scope: :user)
  end
end

You can also use shared examples if you need to test for the same behaviour in multiple cases.

RSpec.shared_examples "requires authentication" do
  before { do_request }
  it "redirects the user to the login page" do
     expect(response).to redirect_to('/login')
  end
end

However running the same specs just to setup the state for tests is going to be a quite slow solution. Test once and then use factories / stubs to setup the dependencies for later tests.

Upvotes: 0

Mateus
Mateus

Reputation: 46

You could also use shared examples in your specs to reuse it.

Rspec.shared_examples "submits a new deal" do |needed_params| 
  # visit 'new' page
  # use capybara to fill out lots of form fields and hit submit

  it "has the correct values" do 
    # test all the values of the created Deal object 
  end
end

And in your code, you can reuse it in a nested context like:

it_behaves_like "submits a new deal", "params1"

or include it in the current context using:

include_examples "submits a new deal", "params"

See: https://relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

Upvotes: 1

chief
chief

Reputation: 1

I prefer to group those behaviors in a module and include it in my features specs.

In your case, I would create a spec/features/common.rb module

# frozen_string_literal: true

module Features
  module Common
    def submit_new_deal
      # visit 'new' page
      # use capybara to fill out lots of form fields and hit submit
    end
end

and include it in spec/rails_helper.rb like this:

 # Include common functionality for features
 config.include Features::Common, type: :feature

Finally reuse it in feature specs:

it "creates a new deal"
  submit_new_deal
  # test all the values of the created Deal object
end

Upvotes: 0

Related Questions