如何在测试夹具中使用act-as-taggable-on?

时间:2016-03-17 16:18:49

标签: ruby-on-rails minitest fixtures acts-as-taggable-on

看起来像act-as-taggable-on在它设置的数据表中使用多态关系。如何在minitest中使用灯具?

我有一个实现Lead的{​​{1}}模型。看起来这会在模型中添加以下内容:

acts-as-taggable

我的潜在客户表:

has_many :taggings, :as => :taggable, :dependent => :destroy, :class_name => "ActsAsTaggableOn::Tagging"
has_many :base_tags, :through => :taggings, :source => :tag, :class_name => "ActsAsTaggableOn::Tag"

由acts-as-taggable-on创建的表:

  create_table "leads", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.string   "phone"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

宝石中有一个标记类,包括:

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree

  create_table "tags", force: true do |t|
    t.string "name"
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree

以下是rails api docs关于多态关系后我的灯具的样子:

belongs_to :tag, :class_name => 'ActsAsTaggableOn::Tag'
belongs_to :taggable, :polymorphic => true
belongs_to :tagger,   :polymorphic => true

但我明白了:

# leads.yml
onetag1:
  name: "OneTag1 Lead"
  email: "lead@onetag1email.com"
  phone: "14120006002"
  base_tags: one
onetag2:
  name: "OneTag2 Lead"
  email: "lead@onetag2email.com"
  phone: "14120006003"

# taggings.yml
one:
  tag: one
  taggable: onetag1 (Lead)
two:
  tag: two
  taggable: onetag2 (Lead)

# tags.yml
one:
  name: "Tag one"
two:
  name: "Tag two"

我也尝试过:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "tag" of relation "taggings" does not exist
LINE 1: INSERT INTO "taggings" ("tag", "taggable") VALUES ('one', 'o...
                                ^
: INSERT INTO "taggings" ("tag", "taggable") VALUES ('one', 'onetag1 (Lead)')

没有# taggings.yml one: taggable: onetag1 (Lead) two: taggable: onetag2 (Lead) 的引用。但是我得到了:

tag

我错过了什么?如何将标签与灯具中的引线相关联?

1 个答案:

答案 0 :(得分:2)

我知道这已经过时了,但对于通过搜索发现这一点的人来说,这就是解决方案(至少在Rails 5中)。

关键在于Rails'文件夹和类名称之间的魔力。因为acts-as-taggable-on在ActsAsTaggableOn命名空间下创建模块,所以需要在名为acts_as_taggable_on的子文件夹中创建灯具

夹具数据

在fixtures文件夹下,标记相关的灯具应位于此处指示的路径中:

# acts_as_taggable_on/taggings.yml
one:
  tag: one
  taggable: onetag1 (Lead)
two:
  tag: two
  taggable: onetag2 (Lead)

# acts_as_taggable_on/tags.yml
one:
  name: "Tag one"
two:
  name: "Tag two"

测试用例中的夹具

要在测试用例中检索标记或标记,请使用以下命令:

setup do
  @tag = acts_as_taggable_on_tags(:one)
  @tagging = acts_as_taggabe_on_taggings(:one)
end