【发布时间】:2012-07-23 12:45:18
【问题描述】:
describe、context、feature、scenario:这四个有什么区别,我什么时候使用它们?
【问题讨论】:
标签: rspec rspec2 rspec-rails
describe、context、feature、scenario:这四个有什么区别,我什么时候使用它们?
【问题讨论】:
标签: rspec rspec2 rspec-rails
context 是describe 的别名,因此它们在功能上是等效的。您可以互换使用它们,唯一的区别是您的规范文件的读取方式。例如,测试输出没有区别。 RSpec 书说:
“我们倾向于将
describe()用于事物,而context()用于上下文”。
我个人喜欢使用describe,但我可以理解为什么人们更喜欢context。
feature 和 scenario 是 Capybara 的一部分,而不是 RSpec,旨在用于验收测试。 feature 等价于describe / context,scenario 等价于it / example。
如果您使用 Capybara 编写验收测试,请使用 feature / scenario 语法,如果不使用 describe / it 语法。
【讨论】:
今天早上,在编写一些规范时,我遇到了同样的问题。通常,我主要使用describe,并没有特别考虑这一点,但是今天早上我处理了很多案例和一个模块的不同规范,所以对于下一个阅读这些规范的开发人员来说,它必须易于理解.所以我问了谷歌,我发现了这个:describe vs. context in rspec,我觉得他的回答很有趣:
根据rspec源码,“context”只是“describe”的一个别名方法,意思是这两种方法在功能上没有区别。但是,通过使用这两种方法,可以帮助您的测试更易于理解。
“describe”的目的是针对一个功能封装一组测试,而“context”是针对同一状态下的一个功能封装一组测试。
所以,依靠这个原则,你会写一个这样的规范:
#
# The feature/behaviour I'm currently testing
#
describe "item ordering" do
# 1st state of the feature/behaviour I'm testing
context "without a order param" do
...
end
# 2nd state of the feature/behaviour I'm testing
context "with a given order column" do
..
end
# Last state of the feature/behaviour I'm testing
context "with a given order column + reverse" do
..
end
end
不确定这是否是普遍接受的规则,但我发现这种方法清晰且很容易掌握。
【讨论】:
扩展皮埃尔的excellent answer,根据to the docs:
特性和场景DSL对应describe和it, 分别。这些方法只是允许功能的别名 规范作为客户和验收测试阅读更多内容。
因此,对于那些熟悉 Mocha 术语 describe 和 it(更适合从用户的角度描述测试的行为,因此 Mocha 主要用作前端测试框架)的人,您可以:
describe 和 it 或其他配对context 块内使用 it
使用第二个选项,您仍然可以遵循“...包装[ping]一组针对同一状态下的一个功能的测试”的意图。
因此您的测试可能如下所示:
#
# The feature/behaviour I'm currently testing
#
describe "item ordering" do
# 1st state of the feature/behaviour I'm testing
context "without an order param" do
# 1st and only test we want to run in this state
it "asks the user for missing order param" do
...
end
end
# 2nd state of the feature/behaviour I'm testing
context "with an invalid order param" do
# 1st test we want to run in this state
it "validates and rejects order param" do
...
end
# 2nd test we want to run in this state
it "returns an error to user" do
...
end
end
# 3rd state of the feature/behaviour I'm testing with multiple tests
context "with a valid order param" do
it "validates and accepts order param" do
...
end
it "displays correct price for order" do
...
end
unless being_audited
it "secretly charges higher price to user" do
...
end
end
end
end
这样您就可以完全跳过 feature 关键字,您可能希望将其用于特定的前端功能,或者如果您正在进行 FDD(功能驱动开发),这可能会让某些人感到不舒服。在此处向您的开发团队征求意见。
警告:不要总是遵循行业标准,想象一下,如果我们按照大众汽车的理念建模所有测试?
【讨论】: