RSpec / FactoryGirl - MongoID嵌入式文档不会持久存在

时间:2013-02-06 13:56:47

标签: ruby unit-testing rspec mongoid factory-bot

拥有以下工厂:

FactoryGirl.define do
  factory :user do
    provider "github"
    sequence(:uid) {|n| "111111#{n}"}
    sequence(:name) {|n| "name#{n}"}
    sequence(:email) {|n| "name#{n}@example.com"}
    sequence(:nickname) {|n| "nick#{n}"}
    sequence(:token) {|n| "111111111111111111111111111111111111111#{n}"}
    watchlists { [ FactoryGirl.build(:watchlist) ] }
  end
  factory :watchlist do
      sequence(:html_url) {|n| "https://github.com/user#{n}/repo#{n}"}
      description "One repo description"
      sequence(:forks) {|n| "1#{n}"}
      sequence(:watchers) {|n| "#{n}"}
      created_at "2012-11-21 00:09:12 UTC"
      pushed_at "2010-04-15 21:11:51 UTC"
      avatar_url "https://avatar.example.com/avatar.png"
  end
end

当我按照以下方式创建工厂时:

let(:user) { FactoryGirl.create :user }

它导致:用户只有持久模型,没有嵌入子项:监视列表:

1.9.3p194 :014 > User.all.entries
  MOPED: 10.8.0.6:27017 COMMAND      database=admin command={:ismaster=>1} (328.6924ms)
  MOPED: 192.168.3.101:27017 COMMAND      database=admin command={:ismaster=>1} (216.3296ms)
  MOPED: 127.0.0.1:27017 COMMAND      database=admin command={:ismaster=>1} (422.3838ms)
  MOPED: 127.0.0.1:27017 QUERY        database=mongoid_test collection=users selector={} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (354.1191ms)
 => [#<User _id: 51126ae3aaa0786654000001, _type: nil, created_at: 2013-02-06 14:38:27 UTC, updated_at: 2013-02-06 14:38:27 UTC, email: "name1@example.com", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, provider: "github", uid: "1111111", name: "name1", nickname: "nick1", token: "1111111111111111111111111111111111111111", secret: nil, user_hash: nil>] 
1.9.3p194 :015 > 

如何保持嵌入式mongoid模型?

1 个答案:

答案 0 :(得分:1)

它应该是持久的,但您需要查询关系。

尝试:

User.first.watchlists

或者在MongoDB shell中,整个文档将按照您的预期打印出来 db.users.find().pretty();

有关MongoDB shell的更多信息:http://docs.mongodb.org/manual/mongo/