如何为抽象类的子类编写测试?Rails要求为父类指定表名吗?

huangapple go评论50阅读模式
英文:

How to write tests for child of abstract class? Rails expects a table name to be specified for the parent?

问题

我有两个相关的类:

```ruby
class A < ApplicationRecord
  self.abstract_class = true
  ...
end
class B < A
  ...
end

我想测试是否可以创建类B:

class BTest < ActiveSupport::TestCase
  test "可以创建B" do
    record = B.create!
    assert record.valid?
  end
end

然而,测试套件似乎不理解A是一个抽象类。它给我以下错误:

BTest#test_can_create_b:
ActiveRecord::TableNotSpecified: A没有配置表。使用A.table_name=来设置一个。
    /Users/<username>/.rvm/gems/ruby-2.7.2/gems/activerecord-7.0.6/lib/active_record/model_schema.rb:577:in `load_schema!'

我尝试在模型文件中添加A.table_name=nil。
我尝试在测试文件中添加A.abstract_class=true。


<details>
<summary>英文:</summary>

I have two related classes:

class A < ApplicationRecord
self.abstract_class = true
...
end
class B < A
...
end


I want to test that class B can be created:

class BTest < ActiveSupport::TestCase
test "can create B" do
record = B.create!
assert record.valid?
end
end


However it seems like the test suite does not understand that A is an abstract class. It gives me the following error:

BTest#test_can_create_b:
ActiveRecord::TableNotSpecified: A has no table configured. Set one with A.table_name=
/Users/<username>/.rvm/gems/ruby-2.7.2/gems/activerecord-7.0.6/lib/active_record/model_schema.rb:577:in `load_schema!'


I tried adding A.table_name=nil in the model file.
I tried adding A.abstract_class=true in the test file.

</details>


# 答案1
**得分**: 1

你可能在你的`test/fixtures`中有一个多余的`as.yml`固定装置,所以测试套件正在尝试填充它并抛出错误。

<details>
<summary>英文:</summary>

You probably have a leftover `as.yml` fixture in your `test/fixtures`, so the test suite is trying to populate that and throwing the error.

</details>



huangapple
  • 本文由 发表于 2023年7月27日 23:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定