How to reuse scenarios within different features with rspec + capybara

荒凉一梦 提交于 2020-02-01 03:42:24

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18709397/how-to-reuse-scenarios-within-different-features-with-rspec-capybara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!