使用 Scenic gem我构建了一个由物化 View 支持的 activerecord 模型
class MatviewSales < ActiveRecord::Base
self.table_name = 'matview_sales'
self.primary_key = :id
belongs_to :user
belongs_to :account
belongs_to :account_manager, class_name: User, foreign_key: 'manager_id'
def self.refresh
Scenic.database.refresh_materialized_view(table_name, concurrently: true)
end
end
我现在正尝试在 RSpec 中测试这个模型,但无论我做什么,我都无法让 Postgres 使用记录填充 View :
> FactoryGirl.create(:sale_item)
> MatviewSales.refresh
> MatviewSales.all
=> #<ActiveRecord::Relation []>
如何使用测试记录填充物化 View ?
最佳答案
刷新物化 View 不会考虑任何尚未提交的事务。
当使用 rspec use_transactional_fixtures
或 DatabaseCleaner.strategy = :transaction
这意味着,您的 View 将看不到任何先前的 FactoryGirl.create
记录。
我使用的解决方案是关闭使用物化 View 的特定测试的事务。
# spec_helper.rb
RSpec.configure do |config|
config.use_transactional_fixtures = false
# ... other configurations
config.around(:each) do |example|
DatabaseCleaner.strategy = example.metadata.fetch(:clean_database_with, :transaction)
DatabaseCleaner.start
example.run
DatabaseCleaner.clean
end
end
# your test
describe MatviewSales, clean_database_with: :truncation do
it 'works :)' do
FactoryGirl.create(:sale_item)
MatviewSales.refresh
expect(MatviewSales.count).to eq 1
end
end
关于ruby-on-rails - 在 Rspec 中测试物化 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230313/