2

我必须在接受嵌套属性的地方建模。我想构建一个测试以确保嵌套属性不能为空白等。我真的不明白如何进行测试。

我的两个简单模型:

# SeoMapping Model
class SeoMapping < ActiveRecord::Base
  belongs_to :mappingtable, :polymorphic => true
  attr_accessible :seo_url
  validates :seo_url, :presence => true, :uniqueness => true   
end

# Page Model
class Page < ActiveRecord::Base
  has_one :seo_mappings, :as => :mappingtable, :dependent => :destroy
  accepts_nested_attributes_for :seo_mappings 
  attr_accessible :content, :h1, :meta_description, :title, :seo_mappings_attributes
  .........
end

这是我的 Page 和 Seo 工厂:

FactoryGirl.define do
  factory :page do |f|
    seo_mapping
    f.title { Faker::Name.name }
    f.h1 { Faker::Lorem.words(5) }
    f.meta_description { Faker::Lorem.words(10) }
    f.content { Faker::Lorem.words(30) }
  end
end

FactoryGirl.define do
  factory :seo_mapping do |f|
    f.seo_url { Faker::Internet.domain_word }
  end
end

我的测试:

require 'spec_helper'

describe Page do
  it "has a valid factory" do
    expect(create(:page)).to be_valid
  end

  # Cant get this spec to work?
  it "it is invalid without a seo_url" do
    page = build(:page)
    seo_mapping = build(:seo_mapping, seo_url: nil)
    page.seo_mapping.should_not be_valid
    # expect(build(:page, :seo_mapping_attributes[:seo_url] => nil)).to_not be_valid
  end

  it "is invalid without a title" do
    expect(build(:page, title: nil)).to_not be_valid
  end
  ...............
end
4

1 回答 1

1

通常对于这类事情,我会使用一个名为shoulda_matchers的 gem 。它使您可以简单地断言您的模型验证特定属性的存在。

it { should validate_presence_of(:seo_url) }
it { should validate_uniqueness_of(:seo_url) }

如果您不想使用 gem,请尝试以下操作:

seo_mapping = build(:seo_mapping, seo_url: nil)
page = build(:page, seo_mapping: seo_mapping)
page.should_not be_valid
于 2012-08-27T10:45:19.533 回答