Rake db:test:prepare不会创建`table view`

joa*_*aga 14 mysql rake ruby-on-rails

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

我使用MySQL Views做到了这一点,除了我的测试,一切都很顺利.似乎数据库清理程序策略不会将数据保存在数据库中,并且我的视图从未被填充.

我从移动的策略: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
Run Code Online (Sandbox Code Playgroud)

当我执行它时:

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
Run Code Online (Sandbox Code Playgroud)

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

有什么想法吗?

更新:

即使使用以下方法仍未创建到架构的视图:

config.active_record.schema_format = :sql
Run Code Online (Sandbox Code Playgroud)

小智 2

有一个很棒的视图宝石,称为Scenic,您可以直接使用它来创建视图,我之前使用过它,它与 Rspec 配合得很好。

这是如何使用它的教程的链接