【问题标题】:How to reuse scenarios within different features with rspec + capybara如何使用 rspec + capybara 在不同功能中重用场景
【发布时间】:2013-09-10 01:21:07
【问题描述】:

假设我想在不同的上下文或“功能”下测试一些场景。

例如,我的场景涉及用户访问某些页面并期望某些 ajax 结果。

但是,在不同的条件或“功能”下,我需要执行不同的“后台”任务来改变应用程序的状态。

在这种情况下,我需要一遍又一遍地运行相同的场景,以确保在应用状态的不同变化下一切正常。

有没有办法在某处定义场景,然后重用它们?

【问题讨论】:

    标签: ruby-on-rails-3 capybara bdd rspec-rails


    【解决方案1】:

    您可以使用shared examples 创建可在多个功能中使用的可重用场景。

    下面是从 relishapp 页面获取的一个基本示例。如您所见,在多个特性中使用相同的场景来测试不同的类——即运行了 6 个示例。

    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
    

    relishapp 页面上有几个示例,包括运行带有参数的共享示例(复制如下)。我猜想(因为我不知道您的确切测试)您应该能够在执行这组示例之前使用这些参数来设置不同的条件。

    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
    

    【讨论】:

    • 错字:collection.size.should eq(3) not eq(2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多