ruby-on-rails-3 – 如何使用rspec capybara重用不同功能中的场景

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 如何使用rspec capybara重用不同功能中的场景前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一些我想在不同的上下文或“功能”下测试的场景.

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

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

在这种情况下,我需要一遍又一遍地运行相同的场景,以确保一切都适用于应用程序状态的不同更改.

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

解决方法

您可以使用 shared examples创建在多个功能中使用的可重用方案.

从relishapp页面获取的基本示例如下.如您所见,在多个功能中使用相同的方案来测试不同的类 – 即运行了6个示例.

  1. require 'rspec/autorun'
  2. require "set"
  3.  
  4. shared_examples "a collection" do
  5. let(:collection) { described_class.new([7,2,4]) }
  6.  
  7. context "initialized with 3 items" do
  8. it "says it has three items" do
  9. collection.size.should eq(3)
  10. end
  11. end
  12.  
  13. describe "#include?" do
  14. context "with an an item that is in the collection" do
  15. it "returns true" do
  16. collection.include?(7).should be_true
  17. end
  18. end
  19.  
  20. context "with an an item that is not in the collection" do
  21. it "returns false" do
  22. collection.include?(9).should be_false
  23. end
  24. end
  25. end
  26. end
  27.  
  28. describe Array do
  29. it_behaves_like "a collection"
  30. end
  31.  
  32. describe Set do
  33. it_behaves_like "a collection"
  34. end

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

  1. require 'rspec/autorun'
  2.  
  3. shared_examples "a measurable object" do |measurement,measurement_methods|
  4. measurement_methods.each do |measurement_method|
  5. it "should return #{measurement} from ##{measurement_method}" do
  6. subject.send(measurement_method).should == measurement
  7. end
  8. end
  9. end
  10.  
  11. describe Array,"with 3 items" do
  12. subject { [1,3] }
  13. it_should_behave_like "a measurable object",3,[:size,:length]
  14. end
  15.  
  16. describe String,"of 6 characters" do
  17. subject { "FooBar" }
  18. it_should_behave_like "a measurable object",6,:length]
  19. end

猜你在找的Ruby相关文章