在 RSpec 中,it_behaves_like
和 include_examples
有什么区别?
include_examples
— include(s) the examples in the current context
it_behaves_like "name"
— include(s) the examples in a nested context
但这到底是什么意思呢?用另一个替换一个似乎对我的测试是通过还是失败没有影响。在某些情况下是否有理由偏爱其中一个?
此外,it_should_behave_like
和 it_behaves_like
只是同义词吗?
最佳答案
您可能知道如何使用describe
、context
、it
和specify
来清楚地传达一个方面你的代码。 it_behaves_like
提供的嵌套上下文可用于改善与读者的这种交流。
我的示例将基于 RSpec 文档中为 shared examples 给出的示例:
shared_examples "a collection" do
context "initialized with 3 items" do
it "says it has three items" do
# ...
end
end
end
describe Array do
it_behaves_like "a collection"
include_examples "a collection"
end
如果您使用 --format documentation
运行 RSpec,您将获得以下输出:
Array
behaves like a collection
initialized with 3 items
says it has three items
initialized with 3 items
says it has three items
所以区别在于如何读取规范,例如在发生故障的情况下。
您喜欢哪种风格是一个审美问题,即您喜欢阅读规范的方式。此外,如果您在团队中工作以提高一致性,您会建议始终使用相同的风格。
Also, are it_should_behave_like and it_behaves_like just synonyms?
几乎,上下文命名不同。 它应该表现得像...
vs 表现得像...
。又是一个美学问题。
关于ruby - "include_examples"和 "it_behaves_like"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556296/