问题
Moingoid doesn't seem to be setting embedded relationships persistently during my tests. In my user model I have:
def vote_on(bill, value)
if my_groups = self.groups
my_groups.each do |g|
bill.votes.create(:value => value, :user_id => self.id, :group_id => g.id)
# result only with factories: bill.votes.first.group = nil
# and bill.votes.first.user = nil !!
# self.id and g.id have good values during the test, they just aren't persisting
end
else
raise "no groups for this user" # #{self.full_name}"
end
end
Other helpful code might be:
## bill model
class Bill
embeds_many :votes
## vote model
class Vote
include Mongoid::Document
field :value, :type => Symbol # can be :aye, :nay, :abstain
#field :group_type, :type => Integer
belongs_to :user
belongs_to :group
embedded_in :bill
end
## test
test "descriptive tally should work" do
user1 = Factory.build(:user)
b = Factory.build(:bill)
user1.vote_on(b, :aye) # nil values created here!
tally = b.descriptive_tally
assert_not_nil tally
end
## bill factory
Factory.define :bill do |f|
f.bill_html "just the facts"
...
f.state "Introduced"
f.text_updated_on DateTime.parse("2011-06-16 00:00:00 Z")
f.text_word_count 2356
f.votes
end
## user factory
Factory.define :user do |u|
u.email 'user@domain.com'
u.name 'user'
u.roles_mask 1
u.password "secret"
u.password_confirmation "secret"
u.groups {[Factory.build(:group, {:name => 'foreign', :type => :custom})]}
end
This is a real head-scratcher for me. Perhaps this is a bug I need to better explore and submit. My first guess is that I am just missing something simple in my factories or test setup. This code works well on development. Any help is greatly appreciated.
回答1:
I think there are issues with most factory gems and Mongoid. I seem to recall having a lot of issues trying to use both Factory Girl and Machinist.
Fabrication seems to be the current recommended standard for doing object generation in tests with Mongoid. It's worked perfectly for us on all our Mongoid projects.
来源:https://stackoverflow.com/questions/6449480/mongoid-not-playing-nicely-with-factories