单元测试与轨道4中的灯具的多态关联

时间:2016-12-24 03:52:05

标签: ruby-on-rails ruby-on-rails-4 activerecord

我需要对每个广告系列都有网址的促销模型进行单元测试。促销和reference_link之间存在多态关联。参考链接夹具:

reference_link:
  linkable: 
    fix_1 (PromoCode)

如何说服rails促销夹具确实有一个属于它的URL?

在促销测试助手中:

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

1 个答案:

答案 0 :(得分:0)

很简单,你几乎做对了。首先,确保正确设置灯具:

# 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'

测试:

# 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

不要忘记文件命名是Rails使用的约定的重要部分。