我刚刚开始测试,我想知道如何编写RSpec规范的步骤,所以我可以重用很多函数,比如登录等等。
答案 0 :(得分:3)
通常测试应该彼此隔离;如果你的很多测试需要做同样的事情,这表明他们正在重复一些工作。但有时候这是不可避免的 - 例如,你经常需要有一个登录用户来测试经过验证的东西。
特别是在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_for
和it_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