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

时间:2016-06-21 20:39:01

标签: mysql ruby-on-rails rspec rake

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

我使用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

当我执行它时:

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

1 个答案:

答案 0 :(得分:1)

视图Scenic有一个很棒的视图宝石,您可以直接使用它来创建视图,我之前使用过它,并且可以与Rspec一起很好地工作。

这里是link,用于指导如何使用它