这是我的工厂:
规格/工厂.rb
FactoryGirl.define do
factory :user do
username 'user1'
time_zone 'Eastern Time (US & Canada)'
email 'user@example.com'
password 'testing'
end
factory :product do
name 'Great Product'
about 'this is stuff about the product'
private false
end
end
我的产品型号:
模型/product.rb
class Product < ActiveRecord::Base
attr_accessible :about, :name, :private
belongs_to :user
has_many :prices
validates_presence_of :name
validates_presence_of :user_id
end
这是我使用 Rspec 和Shoulda寻求帮助的测试:
规格/模型/product_spec.rb
require 'spec_helper'
describe Product do
before(:each) do
FactoryGirl.build(:product)
end
it { should have_many(:prices) }
it { should belong_to(:user) }
it { should validate_presence_of :name }
it { should validate_presence_of :user_id }
end
测试通过了,但我认为我应该为协会这样做:
factory :product do
name 'Great Product'
about 'this is stuff about the product'
private false
user # <--
end
如果我对错误执行此操作,所有测试都将失败:
ActiveRecord::RecordInvalid:
Validation failed: Time zone is not included in the list
那么它真的分配了我在工厂创建的用户吗?
编辑
用户.rb
has_many :products
validates_presence_of :username
validates_presence_of :time_zone
validates_format_of :username, :with => /^(?=(.*[a-zA-Z]){3})[a-zA-Z0-9]+$/
validates_uniqueness_of :email
validates_uniqueness_of :username, :case_sensitive => false
validates_length_of :username, :within => 3..26
validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones