【问题标题】:Rake db:test:prepare does not create `table view`Rake db:test:prepare 不创建“表视图”
【发布时间】:2016-10-23 13:50:44
【问题描述】:

我的项目中有两个结构几乎相同的表,其中一个用于计算用户统计信息,另一个从未用于此目的。现在我需要同时使用它们来计算统计数据。

我使用 MySQL 视图做到了这一点,除了我的测试之外一切都很好。似乎 Database Cleaner 策略不会将数据保存在数据库中,并且我的视图从未被填满。

我将策略从:transaction 移动到:truncation 并且数据开始被持久化。但我仍然有问题,我继续无法从视图中读取数据。

# spec/spec_helper.rb
config.before(:each, using_view: true) do
  DatabaseCleaner.strategy = :truncation
end

# spec/models/stats/answer.rb
describe 'POC test', using_view: true do
  it 'works fine without the table view' do
    expect{ create(:answer) }.to change{ Answer.count }
    expect{ create(:knowledge_answer) }.to change{ Knowledge::Answer.count }
  end

  it 'works fine with the table view' do
    expect{ create(:answer) }.to change{ Stats::Answers.count }
    expect{ create(:knowledge_answer) }.to change{ Stats::Answers.count }
  end
end

当我执行它时:

Stats::Answers
  POC test
    works fine with the table view (FAILED - 1)
    works fine without the table view

Failures:

  1) Stats::Answers POC test works fine with the table view
     Failure/Error: expect{ create(:answer) }.to change{ Stats::Answers.count }
       expected result to have changed, but is still 0
     # ./spec/models/stats/answers_spec.rb:18:in `block (3 levels) in <top (required)>'

Finished in 4.75 seconds (files took 30.37 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/models/stats/answers_spec.rb:17 # Stats::Answers POC test works fine with the table view

经过大量研究,我发现rake db:test:prepare 将视图创建为普通表而不是视图,因为它使用db/schema.rb 生成测试数据库模式。现在我需要了解如何在测试中生成视图而不是普通表。

有什么想法吗?

更新:

即使使用以下方法,仍然没有将视图创建到架构中:

config.active_record.schema_format = :sql

【问题讨论】:

  • 我不认为这个问题真的与 database_cleaner 有关。相反,可能是您的工厂不工作或某些验证失败。数据库清理器在示例之后运行,因此您使用的任何策略都不应影响结果。
  • 如果创建失败,将创建操作更改为 raise 会发生什么? IE更改保存保存!
  • 尝试在测试环境 RAILS_ENV=test bundle exec rake db:migrate 上运行迁移,然后再次运行测试
  • a) 这是一个很好的问题,但我建议将其编辑下来,以便“经过大量研究......”中的问题处于前沿和中心位置。 b) 你试过the gems that add view support to ActiveRecord吗?
  • 不久前,我发现了这个项目github.com/scenic-views/scenic,用于在 Rails 上进行版本控制和管理数据库视图,我知道这可能是一个漫长的过程,但这对你有用。

标签: mysql ruby-on-rails rake


【解决方案1】:

有一个很棒的视图gem,叫做Scenic,您可以直接使用它来创建视图,我以前用过它,它与Rspec配合得很好。

这里是link 的使用教程

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2013-02-16
    • 2013-07-30
    相关资源
    最近更新 更多