rspec共享示例与共享上下文

swa*_*pab 32 ruby rspec ruby-on-rails

shared_examples和之间的真正区别是shared_context什么?

我的观察:

  1. 我可以使用两者测试相同的东西(即带shared_examplesshared_context)

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

观察#1:

我在https://www.relishapp.com/上比较了每个文档的shared_examplesshared_context

语法上的差异是:

  • shared_context用于定义将通过隐式匹配元数据在示例组的上下文中计算的块

示例:

shared_context "shared stuff", :a => :b do
  ...
end
Run Code Online (Sandbox Code Playgroud)
  • 从测试文件中包含或调用它们的方式

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
Run Code Online (Sandbox Code Playgroud)

shared_context

include_context "shared stuff"
Run Code Online (Sandbox Code Playgroud)

观察#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
Run Code Online (Sandbox Code Playgroud)

并将上下文包含在已包含一个shared_context的spec文件中,然后现有文件失败.但是我改变了顺序然后我的所有测试通过

失败

include_context 'existing_shared_context'

include_context 'limit_articles'
Run Code Online (Sandbox Code Playgroud)

另外,如果我取代shared_contextshared_examples,因此它包括在测试案例.

通行证

include_context 'existing_shared_context'

it_behaves_like 'limit_articles'
Run Code Online (Sandbox Code Playgroud)

raf*_*ch2 46

shared_examples是以可以在多个设置中运行它们的方式编写的测试; 提取对象之间的常见行为.

it_behaves_like "a correct object remover" do
    ...
end
Run Code Online (Sandbox Code Playgroud)

shared_contexts是您可以用来准备测试用例的任何设置代码.这允许您包含测试助手方法或准备运行测试.

include_context "has many users to begin with"
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 17

shared_examples 包含一组示例,您可以将其包含在其他描述块中.

A shared_context包含一组共享代码,您可以将其包含在测试文件中.把它想象成一个红宝石模块.

您可以shared_context在测试代​​码中使用a ,并将其包含在include_context方法中.

另一方面,您声明某个behaves_like共享示例组.

我想这是一个可读性的问题.

更新:

如果你查看源代码,你会发现它们完全相同.查看此文件中的第35行:

https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/shared_example_group.rb

alias_method :shared_context,      :shared_examples
Run Code Online (Sandbox Code Playgroud)


hir*_*shi 5

非常微不足道和装饰性,但include_context不会在--format documentation.