Rspec和大规格文件组织

Vit*_*tta 22 ruby testing bdd rspec ruby-on-rails

我只是想知道其他人如何组织大型规范文件(特别是对于模型),其中包含许多上下文和部分,这些文件和描述块中的部分用于验证和其他可以以某种有意义的方式分组的规范.

你们是否在模型的相同spec文件中保留了有关模型的所有规格,或者你是否以某种方式拆分成模块?

到目前为止,我从未关心过这个问题,但我想知道别人做了什么,因为似乎没有就最佳实践或类似问题达成某种协议.

我有一些非常大的规范文件,我想将一些模型组织成较小的文件,并且在不同的模型中几乎没有共享的功能,所以我不确定是否可以使用共享示例(无论可重用性)还是有更好的方法.有什么建议?

提前致谢.

Dav*_*sky 22

嵌套的上下文可以帮助你,但保持浅(通常是一层深).每个示例中要考虑两个变量:givens(起始状态)以及正在调用的方法.您可以按方法或状态对事物进行分组:

# by method
describe Stack do
  describe "#push" do
    it "adds an element to an empty stack"
    it "adds an element to a non-empty stack"
  end

  describe "#pop" do
    it "returns nil from an empty stack"
    it "returns the last element of a non-empty stack"
    it "removes the last element from a non-empty stack"
  end
end

# by state
describe Stack do
  context "when empty" do
    specify "push adds an element"
    specify "pop returns nil"
  end

  context "when not empty" do
    specify "push adds an element"
    specify "pop returns last element"
    specify "pop removes last element"
  end
end
Run Code Online (Sandbox Code Playgroud)

我已经使用了这两种方法,看到它们都工作得很好而且非常糟糕.这两种方法的关键在于,当您从上到下阅读时,示例会讲述一个故事.随着需求的发展,这意味着您需要查看此文件,就像执行实施代码一样.检查规范有意义的简单方法是使用文档格式化程序运行它:

rspec stack_spec.rb --format documentation
Run Code Online (Sandbox Code Playgroud)

这将按顺序吐出所有名称(假设您没有使用--order rand):

Stack
  #push
    adds an element to an empty stack
    adds an element to a non-empty stack
  #pop
    returns nil from an empty stack
    returns the last element of a non-empty stack
    removes the last element from a non-empty stack
Run Code Online (Sandbox Code Playgroud)

要么

Stack
  when empty
    push adds an element
    pop returns nil
  when not empty
    push adds an element
    pop returns last element
    pop removes last element
Run Code Online (Sandbox Code Playgroud)

一旦你看到这个输出,你就会很清楚你正在使用的组织是否有意义.