ruby-on-rails - rspec 共享示例与共享上下文

标签 ruby-on-rails ruby rspec

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

我的观察:

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

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

观察#1:

我比较了shared_examplesshared_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/

相关文章:

ruby-on-rails - rake 数据库 :test:prepare erroring out due to PG error

javascript - 使用 OpenSSL 在 Ruby 中编码和字节错误?

ruby-on-rails - Rails 有两个和多个

ruby-on-rails - Rails 使用逻辑运算符搜索 ActiveRecord

ruby - 使用pry-rescue调试Cucumber步骤异常

ruby - Perl - Ruby 映射?

ruby-on-rails - 无法在 rspec 测试中 stub redis

mysql - 如何有效地将大量数据存储在DB中?

ruby-on-rails - 删除 Rails 中 facebook graph api 发布的帖子上的 "via APP_NAME"

ruby-on-rails - 如何使用Capybara + Selenium测试响应代码