开发者

Ruby on rails, error in unit test

开发者 https://www.devze.com 2023-03-28 19:41 出处:网络
I has one-to many relationship, one group has many servers. To test this relation, i write this test, but it work only when I uncomented line. Why?

I has one-to many relationship, one group has many servers. To test this relation, i write this test, but it work only when I uncomented line. Why?

test 'Group can include server' do
    group = groups(:default)
    group.servers << servers(:default)
    # Test work开发者_开发问答, when I uncomment this line:
    # assert_instance_of Array, group.servers
    group.save
    assert_instance_of Server, group.servers.first
end


Because group.servers isn't an Array. It behaves a lot like one, but it's actually an instance of ActiveRecord::Association::HasManyAssociation. Its ancestor class (ActiveRecord::Association::AssociationProxy) actually passes even class through to an underlying object, so group.servers.class does give Array, but it isn't really one.

Edit: Quick note to say that, while I'm pretty sure this is the reason for your failure, it doesn't make complete sense; in my test apps, the equivalent of group.servers.instance_of? Array is true, and the source of assert_instance_of implies that should be good enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号