Association not finding created objects in tests
I have following models in my app:
class Game < ActiveRecord::Base
has_many :players
has_many :villages, :through => :players
end
class Village < ActiveRecord::Base
belongs_to :player
end
class Player < ActiveRecord::Base
belongs_to :game
has_many :villages
before_create :build_starting_village
protected
def build_starting_village
villages.build(some_attributes)
end
end
I am testing some part of Game functionality with Shoulda/FactoryGirl, this is the test:
setup do
@villages = []
5.times do |i|
p = Factory(:player, :game => @game)
v = p.villages.first
assert v
@villages << v
end
开发者_JS百科 assert_equal @villages.size, @game.villages.size
end
The problem is that the last assert fails. I have tried many ugly things like:
@game.villages(true)
@game.players(true)
@game = Game.find(@game.id)
But I can't see to get to the root of the problem. I have tried disabling transactional fixtures (I do not use fixtures, but I think this also affect Factory girl) and it helped in other tests but here it has no effect.
The assert in the setup block fails in about 1 of 4 runs. I am trying to suspect MySQL... When I debug it from RubyMine everything passes with the reloading statements, but not from command-line.
try asserting something other than truthiness because it could be anything, eg assert_instance_of Village
also what happens in the following case? Forgive me for any slight syntax mistakes, haven't used test::unit/shoulda in a while, but in your code, not sure where @game
comes from
def test_player_has_village_on_new
p = Factory(:player, :game => Factory(:game))
assert_equal 1, p.villages.size
end
精彩评论