2014-08-31 49 views
0

我有以下代碼:Mongoid定製ID和factoryGirl

工廠/ web.rb

FactoryGirl.define do 
    factory :web do 
    name 'Name of web' 
    url 'http://google.es' 

    after(:create) do |web| 
     10.times do |i| 
     web.link << FactoryGirl.create(:link, web: web, url: i, _id: i) 
     end 
    end 
    end 
end 

工廠/ link.rb

factory :link do 
    anchor_text 'anchor' 
    title 'title' 
    code 200 
    sequence :url do |n| 
    "http://google.es/#{n}" 
    end 
end 

型號/ web.rb

class Web 
    include Mongoid::Document 
    (...) 
    has_many :link 
end 

models/link.rb

class Link 
    include Mongoid::Document 
    field :_id, type: String, default: ->{ Digest::MD5.hexdigest(url) } 
    belongs_to :web 
    field :url, type: String 
    (...) 
end 

所以我在鏈接的自定義ID,它工作在開發環境,但是當我跑RSpec的,我在所有測試中獲得:

Failure/Error: Unable to find matching line from backtrace 
TypeError: 
can't convert nil into String 
# ./app/models/link.rb:4:in `digest' 
# ./app/models/link.rb:4:in `hexdigest' 
# ./app/models/link.rb:4:in `block in <class:Link>' 
# ./spec/factories/webs.rb:10:in `block (4 levels) in <top (required)>' 
# ./spec/factories/webs.rb:9:in `times' 
# ./spec/factories/webs.rb:9:in `block (3 levels) in <top (required)>' 
# ./spec/factories/user.rb:8:in `block (3 levels) in <top (required)>' 
# ./spec/rails_helper.rb:43:in `block (2 levels) in <top (required)>' 
# -e:1:in `<main>' 

回答

0

你可以嘗試寫:

factory :link do 
    sequence(:url) { |n| "http://google.es/#{n}" } 

    anchor_text 'anchor' 
    title 'title' 
    code 200 
    url 
end 
+0

它不工作,我會得到一個錯誤: 性狀未註冊 – ie8888 2014-08-31 15:16:13