Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse scenarios within different features with rspec + capybara

Say I have some scenarios that I want to test under different contexts, or "features".

For example, I have scenarios which involve the user visiting certain pages and expecting certain ajax results.

But, under different conditions, or "features", I need to perform different "background" tasks which change the state of the app.

In this case I need to run the same scenarios over and over again to make sure that everything works with the different changes to the state of the app.

Is there a way to define scenarios somewhere, and then reuse them?

like image 236
andy Avatar asked Sep 10 '13 01:09

andy


1 Answers

You can create re-usable scenarios that are used in multiple features by using shared examples.

A basic example, taken from the relishapp page is below. As you can see, the same scenarios are used in multiple features to test different classes - ie there are 6 examples run.

require 'rspec/autorun'
require "set"

shared_examples "a collection" do
  let(:collection) { described_class.new([7, 2, 4]) }

  context "initialized with 3 items" do
    it "says it has three items" do
      collection.size.should eq(3)
    end
  end

  describe "#include?" do
    context "with an an item that is in the collection" do
      it "returns true" do
        collection.include?(7).should be_true
      end
    end

    context "with an an item that is not in the collection" do
      it "returns false" do
        collection.include?(9).should be_false
      end
    end
  end
end

describe Array do
  it_behaves_like "a collection"
end

describe Set do
  it_behaves_like "a collection"
end

There are several examples on the relishapp page, including running the shared examples with parameters (copied below). I would guess (since I do not know your exact tests) that you should be able to use the parameters to setup the different conditions prior to executing the set of examples.

require 'rspec/autorun'

shared_examples "a measurable object" do |measurement, measurement_methods|
  measurement_methods.each do |measurement_method|
    it "should return #{measurement} from ##{measurement_method}" do
      subject.send(measurement_method).should == measurement
    end
  end
end

describe Array, "with 3 items" do
  subject { [1, 2, 3] }
  it_should_behave_like "a measurable object", 3, [:size, :length]
end

describe String, "of 6 characters" do
  subject { "FooBar" }
  it_should_behave_like "a measurable object", 6, [:size, :length]
end
like image 169
Justin Ko Avatar answered Sep 20 '22 19:09

Justin Ko