shared_examples
和 shared_context
之间的真正区别是什么?
我的观察:
我可以使用两者测试相同的东西(即使用
shared_examples
或shared_context
)但是如果我使用后面的测试,我的一些其他测试会失败。
观察#1:
我比较了shared_examples和 shared_context根据 https://www.relishapp.com/ 上的文档
语法差异是:
- shared_context 用于定义一个 block ,该 block 将通过隐式匹配元数据在示例组的上下文中进行评估
示例:
shared_context "shared stuff", :a => :b do
...
end
- 从测试文件中包含或调用它们的方式
共享示例
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
共享上下文
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
并在已经包含一个共享上下文的规范文件中包含上下文,然后现有的失败。但是我改变了顺序然后我所有的测试都通过了
失败
include_context 'existing_shared_context'
include_context 'limit_articles'
此外,如果我将 shared_context
替换为 shared_examples
并将其相应地包含在测试用例中。
通过
include_context 'existing_shared_context'
it_behaves_like 'limit_articles'
最佳答案
shared_examples
是以您可以在多个设置中运行它们的方式编写的测试;提取对象之间的共同行为。
it_behaves_like "a correct object remover" do
...
end
shared_contexts
是您可以用来准备测试用例的任何设置代码。这允许您包含测试辅助方法或准备运行测试。
include_context "has many users to begin with"
关于ruby-on-rails - rspec 共享示例与共享上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117123/