FactoryGirl Has_many通过

时间:2011-12-27 23:10:00

标签: ruby-on-rails cucumber factory-bot

好的,所以我为用户,项目和观看这些项目的能力建立了多对多关联。 (被称为,而不是我曾经提出过的最佳名称“Watchings”)

#project.rb
class Project < ActiveRecord::Base
  has_many :watchings, :foreign_key => "watched_project_id"
  has_many :watchers, :through => :watchings, :source => :user 
end

#user.rb
class User < ActiveRecord::Base
  has_many :watchings
  has_many :watched_projects, :through => :watchings
end

#watching.rb
class Watching < ActiveRecord::Base
  belongs_to :user
  belongs_to :watched_project, :class_name => 'Project'
end

到目前为止,功能上一切正常。我可以观察项目并了解项目有多少观察者。但我的黄瓜功能不断出错,因为我不知道如何让Factory Girl合作。

Factory.define :user do |user|
  user.sequence(:email) {|n| "user#{n}@example.com"}
  user.password "secret"
  user.password_confirmation {|u| u.password }
end

Factory.define :project do |project|
  project.name "Project"
  project.description "Hello World"
end

Factory.define :watchings do |watching|
  watching.association(:user)
  watching.association(:watched_project)
end

我的步骤定义:

Given /^a Project exists called "(.+)" with (\d+) watchers$/ do |project, watchers|
  @project = Factory(:project)
  watchers.to_i.times do |watcher|
    watcher = Factory(:user)
    watching = Factory(:watching)
    watching.user = watcher
    watching.watched_project = @project
  end
end

每当步骤定义运行时,就会惊慌失措并说出

undefined method `watching_user_id=' for #<Watching:0x007ff7800c7978> (NoMethodError)

我尝试了一些不同的东西,但我无法弄清楚如何让它真正成为测试的关联。

2 个答案:

答案 0 :(得分:3)

请注意,您使用较旧的FactoryGirl语法进行工厂定义。

尝试以下方法:

Factory.define :watchings do |watching|
  watching.association(:user)
  watching.association(:watched_project), :factory => :project
end

这应该告诉观看工厂watched_project实际上是project类型。

使用新语法,您的完整工厂定义如下所示:

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "user#{n}@example.com"}
    password "secret"
    password_confirmation {|u| u.password }
  end

  factory :project do
    name "Project"
    description "Hello World"
  end

  factory :watchings do
    user
    association :watched_project, :factory => :project
  end
end

看起来更干净。

答案 1 :(得分:2)

你使用凌乱的命名方法。此外,这里还有Factory Girl示例,该示例应该适用于:

FactoryGirl.define do

  factory :project do
    name "Project"
    description "Hello World"
  end

  factory :user do
    sequence(:email) { |n| "user#{n}@example.com" }
    sequence(:password) { |n| "password#{n}" }
  end

  factory :watching do
    user
    project
  end        
end