【问题标题】:Rake unconsistent behaviour between dev and test?耙开发和测试之间不一致的行为?
【发布时间】:2017-12-21 17:22:29
【问题描述】:

我使用 PostgreSQL 数据库开发了一个 RoR 应用程序,基于这个 database.yml 定义:

    # PostGre databases

    default: &default
      host : localhost
      adapter: postgresql
      encoding: unicode
      pool: 5
      username: keyman
      password: keymanApp
      schema_search_path: "keyman"

    development:
      <<: *default
      database: keyman_dev

    test:
      <<: *default
      database: keyman_test

我创建了一个小型 Rake 例程,因此我可以轻松删除并创建我的 postgreSQL 数据库,包括我使用的架构:

        namespace :db do
            desc 'Create database schemas before going for the first migration'
            task init: ['db:drop','db:create'] do
            ActiveRecord::Base.connection.execute("CREATE SCHEMA keyman AUTHORIZATION keyman")
            puts 'Database initialised'
            end
          end

当我运行 rake db:init 时,它同时在开发和测试环境中执行:

$ rake db:init
Dropped database 'keyman_dev'
Dropped database 'keyman_test'
Created database 'keyman_dev'
Created database 'keyman_test'
Database initialised

但结果不一样:模式“keyman”是为 keyman_dev 数据库创建的,但不是为 keyman_test 数据库创建的。

我需要显式运行 rake db:init RAILS_ENV=test 以获取在测试数据库上创建的架构。

对我来说这听起来很奇怪!你有解释吗? 谢谢

【问题讨论】:

    标签: ruby-on-rails postgresql rake rake-task


    【解决方案1】:

    在运行bin/rake -T db 时,我们可以看到db:createdb:drop 的以下描述

    rake db:create              # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating the development and test databases
    rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to dropping the development and test databases
    

    因此,当您在开发环境中运行这些任务时,它们都会执行 developmenttest 数据库,但这并不意味着其他任务(例如您的自定义任务)会自动在这两种环境中运行,你的任务仍然只在development 环境中运行。

    您的 rake 任务中的类似内容应该让该查询在两个表中运行,尽管这未经测试。

    environments = Rails.env.development? ? [:development, :test] : [Rails.env.to_sym]
    
    environments.each do |env|
      ActiveRecord::Base.establish_connection(env)
      # do something
    end
    

    【讨论】:

    • 感谢您如此清晰的解释,我会在以后的 rake 任务中注意这一点。
    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2021-07-19
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    相关资源
    最近更新 更多