1

私はrspecから始めているので、次の進め方がわかりません:

との間に多対多のテーブルがUserあります。例えばLabelAssignment

  • 「ユーザー A」は「IT」に割り当てられます
  • 「ユーザーB」は「研究」に割り当てられています

製作者:

Fabricator(:label) do
  name { sequence(:name) { |i| "Label #{i}" } }
end

Fabricator(:user) do
  email { sequence(:email) { |i| "user#{i}@email.com" } }
  password 'password'
end

モデル:

class Label < ActiveRecord::Base
  has_many :issues
  has_many :assignments
  has_many :users, :through => :assignments

class User < ActiveRecord::Base
  has_many :assignments
  has_many :labels, :through => :assignments

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :label   
end

class Issue < ActiveRecord::Base

  belongs_to :user
  belongs_to :label

  after_create :print_first_user_label_email

  def print_first_user_label_email
    puts self.label.users.first.email
  end

end

The Issue have to prints users assigned for the issue's label every time I create an issue. But it requires that a label should already has a link with a user (assignment).

So, a simple Fabricate(:issue) will trigger:

let(:issue) { Fabricate(:issue) }

-- Output ---------------------------------------

Failure/Error: let(:issue) { Fabricate(:issue) }
    NoMethodError:
       undefined method `email' for nil:NilClass

So, how do I solve that. Stubbing? Seeding in some way the table? Defining in the fabricators?

Any help will be great!

4

1 に答える 1

1

見た目…物足りない。issue.labelの作り方は?

とりあえず…
[issue_fabricator]

Fabricator(:issue) do
end

【スペック】

let(:label){ Fabricate(:label) }
let(:issue){ Fabricate(:issue, :label=>label) }
#=> undefined method `email' for nil:NilClass

オーケー。そして print_first_user_label_email の作業は...
self #=> issue
.label #=> label
.users #=> [] (空)
.first #=> nil
.email #=> undefined method

やってみなよ:

let(:user) { Fabricate(:user)  }
let(:label){ Fabricate(:label, :users=>[user]) }
let(:issue){ Fabricate(:issue, :label=>label)  }

または before{} ブロックでリレーションを割り当てます。

于 2013-06-04T05:00:03.763 に答える