【问题标题】:Why Rails is creating many test schemas when I am running the tests?为什么在我运行测试时 Rails 会创建许多测试模式?
【发布时间】:2021-04-25 20:49:55
【问题描述】:

当我在我的模型上运行一些测试时,Rails 会在 MySQL 上创建 另外四个测试模式。所以,在我运行:$ bin/rails test 之后,我就有了 Rails 生成的这四个模式。

我也有blog_development,没关系..

我进行了迁移,填充了固定装置并编写了一个示例测试。我在这里有一个示例应用程序:https://github.com/rgiaviti/poc-so-rails-creating-many-test-schemas

下面是我的一些代码:

迁移

class CreateArticles < ActiveRecord::Migration[6.1]
  def up
    create_table :articles do |t|
      t.string :title, null: false
      t.text :body, null: false

      t.timestamps
    end
  end

  def down
    drop_table :articles
  end
end

class CreateComments < ActiveRecord::Migration[6.1]
  def up
    create_table :comments do |t|
      t.references :article, null: false
      t.text :body, null: false

      t.timestamps
    end

    add_foreign_key :comments, :articles
  end

  def down
    remove_foreign_key :comments, :articles
    drop_table :comments
  end
end

夹具

article-1:
  title: This is the Article 1
  body: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In in erat tortor. Proin et dolor vitae erat blandit molestie. Ut vehicula finibus felis, tempor accumsan justo faucibus vitae

article-2:
  title: This the Article 2
  body: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In in erat tortor. Proin et dolor vitae erat blandit molestie.


comment-1:
  article: article-1
  body: A Comment

comment-2:
  article: article-1
  body: "Some Comment"

comment-3:
  article: article-2
  body: Comment for other article

测试

require "test_helper"

class ArticleTest < ActiveSupport::TestCase
  test "should not save article without title" do
    article = Article.new
    article.body = "Body for an Article"
    assert_not article.save
  end
end

我的环境

  • MySQL:8.0.24(与 Docker 一起运行)
  • Rails:Rails 6.1.3.1
  • RVM 版本:rvm 1.29.12;
  • Ruby 版本:ruby 3.0.0p0(2020-12-25 修订版 95aff21468)[x86_64-linux];

【问题讨论】:

    标签: ruby-on-rails testing


    【解决方案1】:

    在您的test/test_helper.rb 中,您有以下指令,我相信这是初始默认测试套件创建的一部分:

    parallelize(workers: :number_of_processors)
    

    这是在核心 Rails 版本 6 中引入的一项功能,它创建独立的测试模式,以便多个测试可以并行运行,而不会干扰彼此的数据库访问。

    有关这方面的更多信息,请参阅 Rails documentationBigBinary 上的功能描述。来自文档:

    将为每个进程创建一个新的数据库,并以工人编号为后缀。

    test-database-0
    test-database-1
    

    【讨论】:

    • 就是这样!谢谢。最后一个问题。你知道为什么当我运行rake db:droprake db:reset 时Rails 不会删除那些数据库(blog_test-0, blog_test-1...)吗?数据库blog_developmentblog_test 被删除。
    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2011-02-10
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多