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 :-)
TY我喜歡早該寶石。但是,如果我嘗試它{應validate_presence_of(:seo_url)}我得到錯誤「未定義的方法'seo_url ='」在我看來,它不喜歡在一個模型上的關聯驗證? – Lee