通过连接表测试简单有很多关联

时间:2014-04-06 16:52:26

标签: ruby-on-rails rspec associations

为了结束我正在进行的练习,我试图通过连接表测试关联。我想要做的是测试艺术家通过艺术作品和收藏品通过艺术作品拥有许多艺术家的许多收藏品的关联。以下是我的代码:

context 'associations' do

let(:artist){ Artist.create(first_name: "Daniel", last_name: "Rubio", 
              email: 'drubs@email.com', birthplace: 'Mexico', 
              style: 'Contemporary') }

let(:art_piece) { ArtPiece.new(date_of_creation: DateTime.parse('2012-3-13'),    
                  placement_date_of_sale: DateTime.parse('2014-8-13'), 
                  cost: 250, medium: 'sculpture', availability: true, artist_id: 
                  artist.id, customer_id: customer.id, 
                  collection_id: collection.id)}

let(:customer) { Customer.create(first_name: 'Carmen', last_name: 'Dent', email:  
                'cdent@email.com', no_of_purchases: 10, amount_spent: 100000) }

let(:collection) { Collection.create(name: 'Romanticism') }

it 'has many collections through art pieces' do
  expect(artist).to respond_to(:collections)
  art_piece.save!
  expect(artist.collections).to eql(collection)
end

end 

现在我很肯定我的关联在我的验证中正确设置了:

class Collection < ActiveRecord::Base
  validates_presence_of :name

  has_many :art_pieces
  has_many :artists, through: :art_pieces
end

class Artist < ActiveRecord::Base
  validates_presence_of :first_name
  validates_presence_of :last_name
  validates :email, presence: true, uniqueness: true
  validates_presence_of :style
  validates_presence_of :birthplace

  has_many :art_pieces
  has_many :collections, through: :art_pieces
end

我遵循了activerecord的指导方针,这对我来说很有意义。我认为发生的唯一两件事是A.我在某处有语法错误或B.我的变量没有被正确链接。任何见解?

以下是我收到的错误消息:

1) Artist associations has many collections through art pieces
 Failure/Error: expect(artist.collections).to eql(collection)

   expected: #<Collection id: 20, name: "Romanticism", created_at: "2014-04-06 16:57:42", updated_at: "2014-04-06 16:57:42">
        got: #<ActiveRecord::Associations::CollectionProxy [#<Collection id: 20, name: "Romanticism", created_at: "2014-04-06 16:57:42", updated_at: "2014-04-06 16:57:42">]>

   (compared using eql?)

   Diff:
   @@ -1,2 +1,2 @@
   -#<Collection id: 20, name: "Romanticism", created_at: "2014-04-06 16:57:42", updated_at: "2014-04-06 16:57:42">
   +[#<Collection id: 20, name: "Romanticism", created_at: "2014-04-06 16:57:42", updated_at: "2014-04-06 16:57:42">]

2 个答案:

答案 0 :(得分:1)

artist.collection返回类似数组的Relation,同时测试它以返回单个ActiveRecord对象。你应该:

expect(artist.collections).to eql([collection])

在你的考试中。

答案 1 :(得分:0)

尝试更改

    expect(artist.collections).to eql(collection)

    expect(artist.collections).to eql([collection])

目前你的rspec期望一个集合对象,但你的查询返回的是一个像对象这样的数组,其中包含一个元素。将期望值更改为您的收藏列表应该可以解决问题。