首页 > 解决方案 > RSpec shared_context 在某些情况下未运行

问题描述

在过去的几天里,我已经实现了这个:

# spec/rails_helper.rb

Dir[Rails.root.join('spec/{support,shared_examples}/**/*.rb')].each { |f| require f }

然后是共享示例之一:

# spec/shared_examples/my_shared_example.rb

RSpec.shared_context 'with tags' do
  before do
    Tag.create!(name: 'foo')
    Tag.create!(name: 'bar')
    Tag.create!(name: 'baz')
  end
end

RSpec.configure do |rspec|
  rspec.include_context 'with tags', tags: true
end

然后在规范本身:

# spec/models/article_spec.rb

require 'rails_helper'

RSpec.describe 'Article' do
  include ActiveSupport::Testing::TimeHelpers

  describe 'tags', :tags do
    let(:tag1) { Tag.find_by(name: 'foo') }
    let(:article) { create(:article, tags: [tag1]) }

    it 'filters based on equity type' do
      puts article.tags
    end
  end
end

但是,create(:article, tags: [tag1])出现“空标签错误”,因为标签foo不存在。使用很明显数据库Tag.find_by!(name: 'foo')bang!没有标签。

为什么我的共享上下文没有运行?我什至将日志放在before do共享上下文中的块中,但它没有运行。共享上下文文件加载,但before do块不去。有什么我想念的想法吗?

我在跑:

rspec spec/models/article_spec.rb

它在其他规范中工作,只是不是这个,我不知道有什么不同或如何调试它。

标签: ruby-on-railsrspec

解决方案


推荐阅读