Question: Unit testing a polymorphic association with fixtures in rails 4

Question

Unit testing a polymorphic association with fixtures in rails 4

Answers 1
Added at 2016-12-24 04:12
Tags
Question

I need to unit test a promotions model where every campaign has a URL. There is a polymorphic association between promotions and reference_link. the reference link fixture reference_link: linkable: fix_1 (PromoCode)

How do I convince rails that the promotions fixture does indeed have a URL belonging to it?

In promotions test helper

test "should have a URL associated with the promo code" do
promo_code = promo_codes(:fix_1)
promo_code.reference_link.url = nil
assert_not promo_code.valid?
promo_code2 = promo_codes(:fix_2)
assert promo_code2.valid?

end

promocode.rb

class PromoCode < ActiveRecord::Base

belongs_to :reward
has_one :reference_link, as: :linkable, dependent: :destroy

validates :email, presence: true
validates :code, presence: true

end

reference_link.rb

class ReferenceLink < ActiveRecord::Base belongs_to :linkable, polymorphic: true,touch: true

 validates :link_name, presence: true
 validates :link_url, presence: true 

 validates_format_of :link_url, :with => /\A#{URI::regexp(['http',    'https'])}\z/

validates_length_of :link_url,:link_name, :maximum => 255  

end

Answers
nr: #1 dodano: 2016-12-30 17:12

It's simple, you almost got it right. First, ensure the fixtures are correctly set:

# promo_codes.yml
promo_1:
  email: 'foobar@gmail.com'
  name: 'Foobar'

# reference_links.yml
reference_1:
  linkable: promo_1
  link_name: 'lorem'
  link_url: 'http://loremipsum.com'

The tests:

# promotion_test.rb
test "should have a URL associated with the promo code" do
  promo_code = promo_codes(:promo_1)

  assert_eq true, promo_code.reference_link.present?
end

Do not forget that file naming is an important part of convention that Rails use.

Source Show
◀ Wstecz