gpt4 book ai didi

ruby-on-rails - RSpec 中的虚拟 ActiveRecord 模型

转载 作者:行者123 更新时间:2023-12-04 05:47:30 25 4
gpt4 key购买 nike

我有一个向 ActiveRecord 添加一些功能的模块。为了测试这个模型,我想在 RSpec 中创建一个虚拟模型,这样我就可以独立于我的生产模型:

describe MyModule do
before do
ActiveRecord::Base.connection.create_table :articles, force: true do |t|
t.string(:name)
end
end

after do
ActiveRecord::Base.connection.drop_table(:articles, if_exists: true)
end

class Article < ApplicationRecord
belongs_to :author
end

class Author < ApplicationRecord
has_many :articles
end

it "does some stuff" do
...
end
end

问题是,Rubocop 向 RSpec/LeakyConstantDeclaration 提示。并建议将固定类提取到 let :
  let(:article_class) do
Class.new(ApplicationRecord) do
has_many :comments
end
end
let(:author_class) do
Class.new(ApplicationRecord) do
has_many :articles
end
end

before do
stub_const("Article", article_class)
stub_const("Author", author_class)
end

当我运行单个测试时,这非常有效。但是当我运行多个测试时,它们会失败,因为缺少文章和/或作者。过去的测试似乎会影响其他测试。

似乎 ActiveRecord 不能很好地处理这种模型定义。所以我想知道是否有更好的方法在 RSpec 中定义虚拟模型?

最佳答案

您可以提取 shared context

RSpec.shared_context 'with test tables  and models' do 
before do
ActiveRecord::Base.connection.create_table :articles, force: true do |t|
t.string(:name)
end

stub_const("Article", article_class)
stub_const("Author", author_class)
end

after do
ActiveRecord::Base.connection.drop_table(:articles, if_exists: true)
end

let(:article_class) do
Class.new(ApplicationRecord) do
has_many :comments
end
end

let(:author_class) do
Class.new(ApplicationRecord) do
has_many :articles
end
end

并将其包含在需要它的每个测试中。

describe MyModule do
include_context 'with test tables and models'

# your examples here
end

关于ruby-on-rails - RSpec 中的虚拟 ActiveRecord 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60184498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com