【问题标题】:Migration not executed from rspec未从 rspec 执行迁移
【发布时间】:2020-11-22 02:10:29
【问题描述】:

我创建了以下迁移脚本(使用bundle exec rails generate migration CreateSequenceStudentId):

class CreateSequenceStudentId < ActiveRecord::Migration[6.0]
  def change
    # Based on: https://schmijos.medium.com/execute-sql-in-rails-migrations-cdb26f51c683
    execute 'CREATE SEQUENCE IF NOT EXISTS student_id;'
  end
end

然后执行bundle exec rails db:migrate RAILS_ENV=test 并完成。我可以使用psql student_test -c"select nextval('student_id')" 访问序列。运行psql student_test -c"select * from schema_migrations sm" 会在最后列出20201122013457。到目前为止没有问题。

然后我编写了以下规范来访问序列:

sql = "select nextval('student_id')"
p Student.connection.select_all(sql)

它失败了:

# --- Caused by: ---
# PG::UndefinedTable:
#   ERROR:  relation "student_id" does not exist
#   LINE 1: select nextval('student_id')

我又执行了一次psql student_test -c"select nextval('student_id')",得到了:

ERROR:  relation "student_id" does not exist
LINE 1: select nextval('student_id')

bundle exec rails db:migrate:status RAILS_ENV=test 给出:

 Status   Migration ID    Migration Name
--------------------------------------------------
...
   up     20201122013457  Create sequence student

表示迁移成功。

psql student_test -c"select * from schema_migrations sm" 给出:

    version
----------------
 20201122013457
 20191209013052
 20191220005953
 20191225001051
 20191225001255
 20191225001458
 ...

首先执行新脚本。这闻起来很腥。

听起来迁移在使用db:migrate 时运行成功,但在运行rspec 时却没有。感谢任何关于我可能做错的指针。

PS:基于this solution,我检查了脚本名称是否唯一。

【问题讨论】:

  • 如果您不怕丢失本地数据,您是否尝试过rails db:reset
  • 运行重置会重新创建序列。问题只是在运行 RSpec 时。

标签: ruby-on-rails activerecord rspec


【解决方案1】:

我可以通过运行以下命令来解决您的问题。我找到了答案here

RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate

更新:

我还找到了修复rails db:reset 命令的方法,您只需在application.rb 中添加行config.active_record.schema_format = :sql,这样有关序列的信息将存储在structure.sql 中。请查看默认模式转储:ruby 中有关序列的信息未存储在schema.rb 文件中。

重要提示:确保先用rails db:migrate创建structure.sql,然后运行rails db:reset。在刚刚rails db:migrate 之后,我仍然收到您要修复的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多