测试 如何用 RSpec 测试多个不同项目的数据库?

zhangjingqiang · September 07, 2016 · Last by zhangjingqiang replied at September 07, 2016 · 6364 hits

现在有一个需求,在项目 1 中要用 rspec 测试外部数据库中数据对此项目数据的影响,为便于说明,起名如下:

  • 现项目名:app1
  • 现项目数据库:database1
  • 外部项目名:app2
  • 外部项目数据库:database2

在 config/database.yml 中添加 app2_test 测试数据库:

app2_test:
  <<: *app2_default
  database: app2_test

在 db/schema.rb 中添加创建 app2 中库的表的 schema:

create_table "products", force: :cascade do |t|
  t.string "name"
end

并用 factory_girl 构建测试数据:factory :product, :class => App2::Product do。 但当我执行 rspec 测试时,显示这样的消息:

Failure/Error: let(:app2_products) { create(:product) }

ActiveRecord::StatementInvalid:
  Mysql2::Error: Table 'app2_test.products' doesn't exist: SHOW FULL FIELDS FROM `products`
# ./spec/my_spec.rb:4:in `block (2 levels) in <top (required)>'
# ./spec/my_spec.rb:12:in `block (3 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# Mysql2::Error:
#   Table 'app2_test.products' doesn't exist
#   ./spec/my_spec.rb:4:in `block (2 levels) in <top (required)>'

怎么建立 app2 中数据库中的表呢?

暂时的方法是在 app2 手动执行:

rake db:migrate RAILS_ENV=test

在 app1 可以测试。

You need to Sign in before reply, if you don't have an account, please Sign up first.