0

我对 FactoryGirl 有疑问。我编写了简单的论坛应用程序并将标签功能添加到主题。一切正常,但我在测试此功能时遇到问题。

这是我的工厂:

FactoryGirl.define do 
  factory :user do 
    sequence(:name)       {|n| "Person #{n}"}
    sequence(:email)      {|n| "person_#{n}@forumapp.com"}
    password              "foobar92"
    password_confirmation "foobar92"
  end
  factory :forum do 
    name "Test Forum"
    description "Test Forum Description"
  end
  factory :tag do 
    name "Test"
  end
  factory :topic do 
    name "Test Topic"
    description "Test Topic Description"
    forum 
    user
  end
  factory :post do 
    content "Lorem ipsum dolor sit amet"
    topic
    user
  end
end

在我的 topic_pages_spec 我正在做这样的事情:

 let(:tag) {FactoryGirl.create(:tag)}
 let(:topic){FactoryGirl.create(:topic, forum: forum, user: user, tags: tag)}

我的标签和主题数据库架构如下所示:

create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "topic_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id", using: :btree
  add_index "taggings", ["topic_id"], name: "index_taggings_on_topic_id", using: :btree

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

  create_table "topics", force: true do |t|
    t.string   "name"
    t.integer  "forum_id",    null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id",     null: false
    t.string   "description"
  end

我的主题模型是:

  has_many :taggings
  has_many :tags, through: :taggings  

标注型号:

  belongs_to :tag
  belongs_to :topic

标签型号:

  has_many :taggings   has_many :topics, through: :taggings

当我尝试运行此规范时,出现以下错误:

 Failure/Error: let!(:topic){FactoryGirl.create(:topic, forum: forum, user: user, tags: tag)}
     NoMethodError:
       undefined method `each' for #<Tag:0x000000078f7210>
     # ./spec/requests/topic_pages_spec.rb:8:in `block (2 levels) in <top (required)>'

我不知道如何测试此功能...

4

1 回答 1

2

你有has_many :tags, through: :taggins- 这意味着Topic在方法创建中需要一个标签数组。我不确定它是否适用于您的情况(您有 option through),但错误表明它尝试迭代tag失败。

尝试添加[]

let(:topic){FactoryGirl.create(:topic, forum: forum, user: user, tags: [tag])}
于 2013-10-04T20:07:55.897 回答