【问题标题】:Mongoid with custom id and factoryGirl具有自定义 id 和 factoryGirl 的 Mongoid
【发布时间】:2014-08-31 15:00:03
【问题描述】:

我有以下代码:

工厂/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

factories/link.rb

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

models/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

所以我在 Link 中有一个自定义 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>'

【问题讨论】:

    标签: ruby-on-rails rspec mongoid factory-bot mongoid3


    【解决方案1】:

    你可以试试写:

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

    【讨论】:

    • 它不起作用,我会得到一个错误:特征未注册
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多