如何通过RSPEC集成正确设置或配置自定义gem

时间:2018-10-02 07:44:41

标签: ruby-on-rails ruby rspec rubygems rspec-rails

我正在做一个简单的gem,并尝试向其中添加rspec。 但是在配置时遇到了麻烦:(

宝石文件

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gemspec

# gem "rails" # as requested
gem 'rspec-rails', '~> 3.7'
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'database_cleaner', '~> 1.5'
gem 'factory_girl_rails', '~> 4.5.0'
gem 'faker', :git => 'https://github.com/stympy/faker.git', :branch => 'master'

my_gem.gemspec

# coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "my_gem/version"

Gem::Specification.new do |spec|
  spec.name          = "my_gem"
  spec.version       = MyGem::VERSION
  spec.authors       = ["Test Test"]
  spec.email         = ["test@gmail.com"]
  ....
  ....
  spec.add_dependency "rails" # as requested
  spec.add_development_dependency "bundler", "~> 1.16"
  spec.add_development_dependency "rake", "~> 10.0"
  spec.add_development_dependency "rspec", "~> 3.0"

end

spec / spec_helper.rb

require 'bundler/setup'
Bundler.setup
require "my_gem"

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = ".rspec_status"

  # Disable RSpec exposing methods globally on `Module` and `main`
  config.disable_monkey_patching!
  # config.include FactoryGirl::Syntax::Methods
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end

test_spec.rb

require 'spec_helper'

RSpec.describe MyGem do
  it "has a version number" do
    expect(MyGem::VERSION).not_to be nil
  end
end

lib / my_gem.rb

require "my_gem/version"
require 'my_gem/engine'

module MyGem
   #....
end

lib / my_gem / engine.rb

require 'my_gem'

module MyGem
  class Engine < Rails::Engine
    isolate_namespace MyGem

    config.generators do |g|
      g.test_framework :rspec
      g.fixture_replacement :factory_girl, :dir => 'spec/factories'
    end

    config.autoload_paths   += Dir.glob(File.join(MyGem::Engine.root, 'app','controllers', '**/'))
  end
end

lib / my_gem / version.rb

module MyGem
  VERSION = "0.1.0"
end

正在运行 ...

bundle exec rspec spec/test_spec.rb 

NameError:
uninitialized constant MyGem::Rails
# ./lib/mu_gem/engine.rb:4:in `<module:MyGem>'

请在添加Rspec时帮助如何正确设置/配置它和其他东西。谢谢!

1 个答案:

答案 0 :(得分:0)

您在代码中引用的是Rails::Engine,但是您的依赖项中没有rails的宝石。