在RSpec中,it_behaves_like
和include_examples
有什么区别?
documentation表示:include_examples
-包括当前上下文中的示例it_behaves_like "name"
-在嵌套上下文中包含示例
但是这实际上意味着什么呢?用一个替换另一个似乎对我的测试是通过还是失败没有影响。在某些情况下,有理由更喜欢一个吗?it_should_behave_like
和it_behaves_like
是同义词吗?
在RSpec中,it_behaves_like
和include_examples
有什么区别?
documentation表示:include_examples
-包括当前上下文中的示例it_behaves_like "name"
-在嵌套上下文中包含示例
但是这实际上意味着什么呢?用一个替换另一个似乎对我的测试是通过还是失败没有影响。在某些情况下,有理由更喜欢一个吗?it_should_behave_like
和it_behaves_like
是同义词吗?
3条答案
按热度按时间siv3szwd1#
您可能知道如何使用
describe
、context
、it
和specify
来清楚地传达代码的某个方面。it_behaves_like
提供的嵌套上下文可用于改善与读者的这种沟通。我的示例将基于shared examples的RSpec文档中给出的示例:
如果使用
--format documentation
运行RSpec,则会得到以下输出:因此,不同之处在于如何读取规范,例如在失败的情况下。
你喜欢哪种风格是一个美学问题,你喜欢你的规格阅读。此外,你会建议总是使用相同的风格,如果你在一个团队中工作,以提高一致性。
另外,it_should_behave_like和it_behaves_like是否只是同义词?
几乎,上下文的命名不同。
it should behave like ...
vsbehaves like ...
。再次是美学问题。fd3cxomn2#
这里有是的区别,如果你传递参数给shared_examples。
在警告in their doc中解释得很好:
警告:当你在当前上下文中多次包含参数化的示例时,你可能会覆盖以前的方法定义,最后一个声明获胜。
你实际上是这样做的(注意第一个例子会失败):
为了防止这种微妙的错误,如果您在同一上下文中声明多个同名方法,则会发出警告。如果您收到此警告,最简单的解决方案是将include_examples替换为it_behaviors_like,这样可以避免方法重写,因为it_behaviors_like创建了嵌套的上下文
plicqrtu3#
在使用
shared_examples
方法时,我发现it_behaves_like
和include_context
之间有很大的区别。当你使用
include_context
时,你可以在你的shared_examples
块中定义let
,before
和it
语句。我想你可能也可以使用context
和describe
块。但是如果你使用
it_behaves_like
,你可以在你的共享示例中使用it
语句,但是如果你在你的shared_example
上定义了一些let
块,它们就不能在包含it_behaves_like
语句的原始rspec.describe
块中使用。我认为这是一个巨大的差异。
同样适用于
include_examples
。我认为可能include_examples
和include_context
非常相似。