ChatGPT解决这个技术问题 Extra ChatGPT

RSpec:描述、上下文、特征、场景?

describecontextfeaturescenario:这四个有什么区别,我什么时候使用它们?


M
M.javid

contextdescribe 的别名,因此它们在功能上是等效的。您可以互换使用它们,唯一的区别是您的规范文件的读取方式。例如,测试输出没有区别。 RSpec 书说:

“我们倾向于将 describe() 用于事物,将 context() 用于上下文”。

我个人喜欢使用 describe,但我可以理解为什么人们更喜欢 context

featurescenario 是 Capybara 的一部分,而不是 RSpec,旨在用于验收测试。 feature 相当于 describe / contextscenario 相当于 it / example

如果您使用 Capybara 编写验收测试,请使用 feature / scenario 语法,如果不使用 describe / it 语法。


Sam 说得很对,这里有一个链接,其中包含更多详细信息和优秀示例,特别是关于 Capybara 内置 DSL(域特定语言)的部分:github.com/jnicklas/capybara#using-capybara-with-rspec
C
Community

今天早上,在写一些规范时,我遇到了同样的问题。通常,我主要使用 describe 并没有特别考虑这一点,但今天早上我处理了很多案例和一个模块的不同规范,因此对于下一个将阅读这些规范的开发人员来说,它必须易于理解.所以我向谷歌询问了这个问题,我发现了这个:describe vs. context in rspec,我觉得他的回答很有趣:

根据rspec源码,“context”只是“describe”的别名方法,意思是这两种方法在功能上没有区别。但是,通过使用这两种方法,存在上下文差异有助于使您的测试更易于理解。 “描述”的目的是针对一个功能包装一组测试,而“上下文”是针对同一状态下的一个功能包装一组测试。

所以,依靠这个原则,你会写一个这样的规范:

#
# 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

不确定这是否是普遍接受的规则,但我发现这种方法清晰且很容易掌握。


这是描述/上下文的一个很好的答案。但是您忘记了有关功能/场景的另一半问题-但是我认为可以(并且应该)以与您为描述/上下文指出的完全相同的方式使用它们。
如果您通过对功能/场景的解释来扩展它,那就太好了!
G
GrayedFox

根据 to the docs,扩展 Pierre 的 excellent answer

特性和场景 DSL 分别对应于 describe 和 it。这些方法只是允许功能规范作为客户和验收测试阅读更多内容的别名。

因此,对于那些熟悉 Mocha 术语 describe 和 it(更适合从用户的角度描述测试的行为,因此 Mocha 主要用作前端测试框架)的人,您可以:

选择始终且仅使用 describe 和 it 或其他配对

选择在需要在特定应用程序状态下进行多个断言/测试的上下文块内使用它

使用第二个选项,您仍然可以遵循“...wrap[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(功能驱动开发),这可能会让某些人感到不舒服。在此处询问您的开发团队的意见。

警告:不要总是遵循行业标准,想象一下如果我们按照大众汽车的理念模拟我们的所有测试?