2017-02-17 59 views
1

我有一個卡廠(定義見下文),FactoryGirl InvalidFactoryError NoMethodError

FactoryGirl.define do 
    factory :card do 
    front { Faker::Lorem.sentence } 
    back { Faker::Lorem.sentence } 
    tags { Faker::Lorem.words(3).join(';') } 

    # associations 
    user 
    tag 
    end 
end 

當我嘗試運行規範我碰到下面的錯誤,

An error occurred in a `before(:suite)` hook. 
Failure/Error: FactoryGirl.lint 

FactoryGirl::InvalidFactoryError: 
    The following factories are invalid: 

    * card - undefined method `each' for "eum;et;ad":String (NoMethodError) 

我不知道這是爲什麼發生的事情,下面的代碼是我的名片模型,

class Card < ApplicationRecord 
    validates :front, presence: true 

    belongs_to :user 
    has_one :meta_sm2 
    has_many :action_records 
    has_and_belongs_to_many :tags 

    delegate :username, :email, :name, 
      to: :user, prefix: true 
end 
+0

什麼是'之前(:套件)' –

+1

'tags {Faker :: Lorem.words(3).join(';')}'期待一個數組而不是字符串 – Sravan

+1

試試這個。 'tags {Faker :: Lorem.words(3)}'而不是標籤'{Faker :: Lorem.words(3).join(';')}' – Sravan

回答

0

由於cardmany-manytags

tags協會預計的array,而是你通過一個字符串,

嘗試,tags { Faker::Lorem.words(3) },而不是tags { Faker::Lorem.words(3).join(';') }

FactoryGirl.define do 
    factory :card do 
    front { Faker::Lorem.sentence } 
    back { Faker::Lorem.sentence } 
    tags { Faker::Lorem.words(3) } 

    # associations 
    user 
    tag 
    end 
end 
0

我已經解決了通過更改出廠代碼問題到下面的代碼,

FactoryGirl.define do 
    factory :card do 
    front { Faker::Lorem.sentence } 
    back { Faker::Lorem.sentence } 

    # associations 
    user 
    tag 
    meta_sm2 
    action_record 
    end 
end 

我認爲上一個問題與缺失的關聯有關。

1

好的,你有一個cardstags之間的HABTM協會。我真的不明白你怎麼能設置tags只有數組或一個字符串,而不是相關的對象,但我仍然相信,要樹立正確的HABTM協會在工廠和一個可以是這樣做的:

FactoryGirl.define do 
    factory :card do 
    front { Faker::Lorem.sentence } 
    back { Faker::Lorem.sentence } 
    # tags { Faker::Lorem.words(3).join(';') } 

    # associations 
    user 


    factory :card_with_tags do 
     after(:create) do |book| 
     create_list(:tag, 3, cards: [card]) 
     end 
    end 
    end 
end 

這是在工廠建立HABTM的「輕量級」方式。我在最近的答案中提到了one中的「徹底」方法。