Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake db:test:prepare does not create `table view`

I have two tables with the almost same structure in my project, one of them was used to calculate user statistics and the another was never being used for that. Now I need to calculate statistics using both of them.

I did that using MySQL Views, everything went fine except for my tests. Seems that Database Cleaner strategy does not save the data on the database and my view never was filled.

I moved the strategy from :transaction to :truncation and the data started to be persisted. But I still with on problem, I continue can't read the data from the view.

# 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

And when I execute it:

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

After a lot of research I found out that the rake db:test:prepare was creating the view as a normal table and not as a view, since it use the db/schema.rb to generate the test database schema. Now I need to discover how to generate the view in the test instead of a normal table.

Any thoughts?

UPDATE:

Still not creating the views into schema even using:

config.active_record.schema_format = :sql
like image 936
joaofraga Avatar asked Jun 21 '16 20:06

joaofraga


1 Answers

There is a great gem for views called Scenic which you can use directly to create the views, I used it before and it works fine with the Rspec.

Here is a link for a tutorial how to use it

like image 163
melsatar Avatar answered Oct 13 '22 07:10

melsatar