【问题标题】:Testing a gem that uses ActiveRecord models using Postgres + Rspec使用 Postgres + Rspec 测试使用 ActiveRecord 模型的 gem
【发布时间】:2017-03-08 22:34:36
【问题描述】:

我正在尝试使用 Rspec 和 Postgres 在 gem 中测试一些模型。目前尝试通过在 spec_helper.rb 文件中运行 rake 任务来完成此操作,该任务将在我的 Rspec 测试期间建立 pg 数据库连接。

我已经扫描了其他问题(我的方法主要基于这两个问题12) 并没有找到好的解决方案。

由于我们的代码编写方式,我没有使用 sqlite in-memory db 功能。

自定义 spec_helper 如下所示:

RSpec.configure do |config|
  load "support/schema.rb"
  load File.expand_path("../../../lib/tasks/database.rake", __FILE__)
  require File.dirname(__FILE__) + 'support/models.rb'
  Rake::Task['database'].invoke

但是,当我运行 rspec 时,它告诉我没有连接池:

active_record/connection_adapters/abstract/connection_pool.rb:570:in
`retrieve_connection': No connection pool for ActiveRecord::Base
(ActiveRecord::ConnectionNotEstablished)

有人对此问题有任何建议或见解吗?将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    你应该建立数据库连接:

    ActiveRecord::Base.establish_connection(adapter: 'postgresql', 
      encoding: 'unicode', database: '<db_name>', username: '<user>')
    

    这应该在任何其他数据库交互之前运行(包括加载schema.rb

    【讨论】:

    • 这是我在 rake 中的数据库任务:desc "Establishes postgresql connection"task :database do`ActiveRecord::Base.establish_connection(``适配器:'postgresql',``主机:'tmp',``数据库: '用户',` `用户名:'用户',` `密码:'',` `端口:5432,` `)` `end`
    • 我认为你应该在建立数据库连接后load "support/schema.rb"
    • 这解决了错误 - 连接到数据库仍然存在一些问题,但似乎必须在加载文件之前建立连接。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多