【问题标题】:rspec shared examples vs shared contextrspec 共享示例与共享上下文
【发布时间】:2014-01-14 15:19:28
【问题描述】:

shared_examplesshared_context 之间的真正区别是什么?

我的观察:

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

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

观察 #1:

我根据https://www.relishapp.com/ 上的文档比较了shared_examplesshared_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 examplesShared context
  • 我已经用示例和详细观察更新了我的问题。
  • 观察 2 包含测试。它应该是一个共享的示例组。这只是关于测试的可读性。

标签: ruby-on-rails ruby rspec


【解决方案1】:

shared_examples 是以一种可以在多种设置中运行它们的方式编写的测试;提取对象之间的共同行为。

it_behaves_like "a correct object remover" do
    ...
end

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

include_context "has many users to begin with"

【讨论】:

  • 感谢您的回答。我已经用示例和详细观察更新了我的问题。
【解决方案2】:

shared_examples 包含一系列示例,您可以将其包含在其他描述块中。

shared_context 包含一组共享代码,您可以将其包含在测试文件中。把它想象成一个 ruby​​ 模块。

通过将include_context 方法包含在测试代码中,您可以在测试代码中使用shared_context

另一方面,您声明某事物behaves_like 是一个共享示例组。

我猜这是可读性的问题。

更新:

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

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

alias_method :shared_context,      :shared_examples

您还会看到shared_examples_for 是同一方法的另一个别名。

【讨论】:

  • 感谢您的回答。我理解这个理论,但它看起来与我几乎相似,除了几个语法差异。我已经用示例和详细观察更新了我的问题。
  • 这真的很简单......将测试放入您希望多个事物符合的共享示例中。将代码放入需要包含在多个测试中的共享上下文中。
【解决方案3】:

非常琐碎和美观,但include_context 不会在--format documentation 中输出“表现得像”。

【讨论】:

    【解决方案4】:

    这是 Rudy Jahchan 的一篇精彩文章,它不仅展示了如何同时使用 shared_contextshared_example,还展示了为什么它们很有价值。
    它通过获取规范然后重构(干燥)它以使用 shared_exampleshared_context 来实现这一点。

    BDD Composition over Inheritance with RSpec Shared Examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多