【问题标题】:Writing steps in rspec-rails?在 rspec-rails 中编写步骤?
【发布时间】:2011-07-09 14:45:45
【问题描述】:

我刚刚开始测试,我想知道如何为 RSpec 规范编写步骤,以便我可以重用很多功能,例如登录等。

【问题讨论】:

    标签: ruby-on-rails rspec automated-tests rspec-rails


    【解决方案1】:

    通常测试应该彼此隔离;如果你的很多测试都需要做同样的事情,这表明他们在重复一些工作。但有时这是不可避免的——例如,您经常需要一个方便的登录用户来测试经过身份验证的东西。

    特别是在 Ruby 测试的情况下,很有可能有人已经编写了一个库来解决您想要的特定问题。例如,在正确测试操作之前需要一些数据是很常见的——这就是 factory_girl 存在的原因。

    如果您想进行行为驱动的集成测试以遍历用户实际执行的所有步骤,则应改用Cucumber

    如果你想跨地方复用方法,可以把共享代码放在spec/support

    # spec/support/consumable_helper.rb
    module ConsumableHelper
      def consume(consumable)
        calories = consumable.om_nom_nom
      end
    end
    
    RSpec.configure do |config|
      config.include ConsumableHelper
    end
    

    如果您想在多个区域测试相同的行为,请使用shared_examples_forit_behaves_like

    shared_examples_for "a Consumable" do
      it "should be delicious" do
        subject.should be_delicious
      end
    
      it "should provide nutrition" do
        subject.calories.should > 0
      end
    end
    
    describe Fruit do
      it_behaves_like "a Consumable"
    end
    
    describe Meat do
      it_behaves_like "a Consumable"
    end
    

    【讨论】:

    • 不相关的旁注。我更喜欢使用不定冠词...shared_examples_for "a Consumable"it_behaves_like "a Consumable"。我只是发现 DSL 读起来更好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多