ruby-on-rails - 在 Rspec 中测试物化 View

标签 ruby-on-rails postgresql rspec materialized-views

使用 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_fixturesDatabaseCleaner.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

documentation about use_transactional_fixtures

关于ruby-on-rails - 在 Rspec 中测试物化 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230313/

相关文章:

ruby-on-rails - Rails 命名空间路由和资源上的自定义操作

ruby-on-rails - Rails - 测试使用 DateTime.now 的方法

postgresql - 亚马逊 Redshift : Is it possible to return multiple result set?

ruby-on-rails - 需要帮助解决失败的 Rspec 测试 - 参数错误 : Comparison of Date with nil

ruby - rspec模拟与其他模拟框架的优缺点是什么?

ruby-on-rails - Rake 中止,无法连接到 postgresql : connection refused

ruby-on-rails - 回形针验证导致Rails 3错误

c++ - 在 Xubuntu 上使用 SOCI(sql 包装器),简单程序在编译时失败

postgresql - 完整的 db 子字符串搜索区分大小写(不)

ruby-on-rails - 您已经激活了 rspec-support 3.0.0.beta1,但是您的 Gemfile 需要 rspec-support 3.0.0.beta1