【发布时间】:2014-01-14 15:19:28
【问题描述】:
shared_examples 和 shared_context 之间的真正区别是什么?
我的观察:
我可以使用两者测试相同的东西(即使用
shared_examples或shared_context)但是如果我使用后面的测试,我的其他一些测试会失败。
观察 #1:
我根据https://www.relishapp.com/ 上的文档比较了shared_examples 和shared_context
语法差异是:
- shared_context 定义一个块,该块将通过隐式匹配元数据在示例组的上下文中进行评估
例子:
shared_context "shared stuff", :a => :b do
...
end
- 在测试文件中包含或调用这些的方式
shared_examples
include_examples "name" # include the examples in the current context
it_behaves_like "name" # include the examples in a nested context
it_should_behave_like "name" # include the examples in a nested context
shared_context
include_context "shared stuff"
观察 #2
我有一个测试用例
shared_context 'limit_articles' do |factory_name|
before do
@account = create(:account)
end
it 'should restrict 3rd article' do
create_list(factory_name, 3, account: @account)
article4 = build(factory_name, account: @account)
article4.should be_invalid
end
it 'should allow 1st article' do
...
end
it 'should allow 2nd article' do
...
end
end
并将上下文包含在一个已经包含一个 shared_context 的规范文件中,那么现有的会失败。但是我改变了顺序,然后我的所有测试都通过了
失败
include_context 'existing_shared_context'
include_context 'limit_articles'
另外,如果我将 shared_context 替换为 shared_examples 并相应地将其包含在测试用例中。
通过
include_context 'existing_shared_context'
it_behaves_like 'limit_articles'
【问题讨论】:
-
rspec文档中的以下页面应该告诉您它们的用途:Shared examples、Shared context -
我已经用示例和详细观察更新了我的问题。
-
观察 2 包含测试。它应该是一个共享的示例组。这只是关于测试的可读性。
标签: ruby-on-rails ruby rspec