如何防止RSpec在带有虚拟应用程序的Rails插件中运行两次规范?



我正在编写一个Rails扩展。为了测试它,我使用 RSpec。为了制作模型来测试插件,我使用了一个预生成的虚拟应用程序:

rails plugin new yaffle --dummy-path=spec/dummy --skip-test --full

我有一些测试。当我打电话给他们时,他们跑了两次。

> # I have 4 tests in app total
> rspec
> 8 examples, 0 failures
> rspec spec/yaffle/active_record/acts_as_yaffle_spec.rb
> 4 examples, 0 failures
> rspec spec/yaffle/active_record/acts_as_yaffle_spec.rb:4
> 2 examples, 0 failures

这是我的文件的样子:

# lib/yaffle.rb
Gem.find_files('yaffle/**/*.rb').each { |path| require path }
module Yaffle
# Your code goes here...
end
# spec/spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
RSpec.configure do |config|
config.example_status_persistence_file_path = '.rspec_status'
config.disable_monkey_patching!
end
# spec/dummy/config/environment.rb
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
# spec/yaffle/active_record/acts_as_yaffle_spec.rb
require "spec_helper"
RSpec.describe "Acts as yaffle" do
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
end
# spec/dummy/config/application.rb
require_relative 'boot'
require "rails/all"
Bundler.require(*Rails.groups)
require "yaffle"
module Dummy
class Application < Rails::Application
config.load_defaults 6.0
end
end

另外,我注意到只有带有require "spec_helper"的文件是重复的

那么,我做错了什么?而且,如果它是一个错误,如何解决它?

原因

它是由这句话引起的:

Gem.find_files('yaffle/**/*.rb').each { |path| require path }

显然,Gem.find_files获取 gem 目录中与该模式匹配的所有文件 - 而不仅仅是相对于 gem 根目录的文件。因此,yaffle/**/*.rb意味着<GEM_ROOT>/lib/yaffle/...<GEM_ROOT>/spec/lib/yaffle/...中的文件。

https://apidock.com/ruby/v1_9_3_392/Gem/find_files/class

修复

我通过明确要求所有文件来修复它:

require 'lib/yaffle/active_record/acts_as_yaffle'
require 'lib/yaffle/active_record/has_fleas'

也可以只要求该目录中的所有文件:

Dir["lib/yaffle/active_record/**/*.rb"].each {|file| require file }

最新更新