2016-12-24 102 views
0

我需要單元測試一個促銷模型,其中每個廣告系列都有一個URL。促銷活動和reference_link之間存在多態關聯。參考鏈接夾具 reference_link: linkable: fix_1 (PromoCode)單元測試與rails中的燈具的多態關聯4

我該如何說服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? 

promocode.rb

類促銷碼<的ActiveRecord ::基地

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

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

reference_link.rb

類ReferenceLink <的ActiveRecord :: Base的 belongs_to的:可連接,多態:真,摸:真

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 

回答

0

這很簡單,你幾乎是正確的。首先,確保燈具的設置是否正確:

# promo_codes.yml 
promo_1: 
    email: '[email protected]' 
    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的使用。