2012-08-27 61 views
2

我是rails TDD的新手,所以请随身携带。我必须模拟我接受嵌套属性的位置。我想建立一个测试,以确保嵌套属性不能为空等。我真的不明白我如何进行测试。Rails Rspec&FactoryGirl测试协会

我的两个简单的模型:

# 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 

这里是我的第工厂和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 

希望你可以建议新手TDD :-)

回答

1

通常对于这类事情我使用一种叫做shoulda_matchers的宝石。它可以让你简单地断言你的模型验证了特定属性的存在。

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

如果你不想使用宝石,尝试这样的事情:

seo_mapping = build(:seo_mapping, seo_url: nil) 
page = build(:page, seo_mapping: seo_mapping) 
page.should_not be_valid 
+0

TY我喜欢早该宝石。但是,如果我尝试它{应validate_presence_of(:seo_url)}我得到错误“未定义的方法'seo_url ='”在我看来,它不喜欢在一个模型上的关联验证? – Lee