微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 使用RSpec加载ActiveRecord灯具而不使用Rails

我在Rails之外使用一些ActiveRecord模型,我正在编写单元测试.在我的测试中,我希望能够使用灯具,并认为我会使用一些 rspec-rails功能.我不能简单地使用require“rspec-rails”,因为它有一些Rails依赖项,我不使用Rails.

这是我正在使用的spec_helper:

require 'active_record'
require 'active_record/fixtures'
require 'active_support'
require 'rspec/rails/extensions/active_record/base'
require 'rspec/rails/adapters'
require 'rspec/rails/fixture_support'  # Includes ActiveRecord::TestFixtures
                                       # into the RSpec config

require 'my_models'

# Setup database connection
environment = "test"
configuration = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(configuration[environment])

RSpec.configure do |config|
  config.fixture_path = File.expand_path("../../test/fixtures",__FILE__)

  # If you're not using ActiveRecord,or you'd prefer not to run each of your
  # examples within a transaction,remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it,you can fix the order by providing
  # the seed,which is printed after each run.
  #     --seed 1234
  config.order = "random"

  # Run each test inside a DB transaction
  config.around(:each) do |test|
    ActiveRecord::Base.transaction do
      test.run
      raise ActiveRecord::Rollback
    end
  end
end

这是一个测试的例子

require 'spec_helper'

describe Transaction do

  before :each do
    self.class.fixtures :users,:merchants
  end

  it "should do this and that" do
    ...
  end
end

问题是,这样,夹具没有加载.我查看了rspec-rails代码,但无法弄清楚我应该扩展哪个模块或我应该调用方法.

解决方法

在深入了解Active Record代码后,我发现没有加载灯具的原因是因为我没有设置ActiveRecord :: Base.configurations.以下解决了这个问题:
configuration = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.configurations = configuration

原文地址:https://www.jb51.cc/ruby/270301.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐