分享的例子共享上下文之间的真正区别是什么?

我的观察:

  1. 我可以用这两种方法测试相同的东西(即分享的例子共享上下文)

  2. 但如果我使用后面的测试,我的其他一些测试就会失败.

Observation #1 :

我比较了https://www.relishapp.com/份文档中的分享的例子份和共享上下文

句法上的差异是:

  • 共享上下文 to define a block that will be evaluated in the context of example groups by implicitly matching metadata

例子:

共享上下文 "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"

Observation #2

我有一个测试用例

共享上下文 '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

And include the context in a spec file which already has one 共享上下文 included, then the existing one fails. But I change the order then all my test passes

Fails

include_context 'existing_共享上下文'

include_context 'limit_articles'

Also if I replace the 共享上下文 with 分享的例子 and accordingly include it in test case.

Passes

include_context 'existing_共享上下文'

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相关问答推荐

本地主机的上衣配置

RubyOnRail在测试环境中启动失败

使用ActiveSupport::TimeWithZone将UTC转换为用户定义的时区

根据表单内的 Select 字段值渲染部分内容

我可以向 erb 变量插值添加一个类吗?

如何断言 Ruby 单元测试中的错误消息?

带有块捕获的 FormBuilder 辅助方法在 ERB 中不起作用

Rails 7 共享刺激控制器功能

Rails 4 中的 null_session 和 reset_session 有什么区别?

如何使用默认的 Rails 记录器记录 Ruby 异常的整个回溯?

Rails 3 中图像路径的完整 url

基于 2 列定义唯一主键

跳过模型中的某些验证方法

fields_for 表单构建器对象为零

是否可以在 Rails 中否定范围?

.increment vs += 1

在 where 查询中查找 nil has_one 关联

在 ruby​​ 中构建公钥时,是什么导致既不是 PUB key 也不是 PRIV key::nested asn1 错误?

如何为rails中的number_field添加默认值?

Rails:一次添加多个 flash[:notice] 的简单方法