我有两个相关的模型:
class User < ActiveRecord::Base
belongs_to :role, dependent: :destroy, polymorphic: true
validates :role, presence: true
end
class Admin < ActiveRecord::Base
has_one :user, as: :role
attr_accessible :user_attributes
accepts_nested_attributes_for :user
end
如果我保存管理员,如何验证用户是否存在?
更新
这是我的测试:
工厂.rb
FactoryGirl.define do
sequence :email do |n|
"foo#{n}@example.com"
end
factory :user do
email
password "secret12"
password_confirmation "secret12"
factory :admin_user do
association :role, factory: :admin
end
end
factory :admin do
first_name "Max"
last_name "Mustermann"
end
end
user_spec.rb
require "spec_helper"
describe User do
let(:user) { FactoryGirl.build(:user) }
let(:admin) { FactoryGirl.build(:admin_user) }
describe "sign up" do
it "should not be valid without associated role" do
user.should_not be_valid
end
it "should be valid with associated role" do
admin.should be_valid
end
end
end
admin_spec.rb
require "spec_helper"
describe Admin do
let(:admin_base) { FactoryGirl.build(:admin) }
let(:admin_user) { FactoryGirl.build(:admin_user).admin }
describe "sign up" do
it "should not be possible without associated user" do
admin_base.should_not be_valid
end
end
it "should have a first name" do
admin_user.first_name = ""
admin_user.should_not be_valid
end
it "should have a last name" do
admin_user.last_name = ""
admin_user.should_not be_valid
end
it "should create a correct full name" do
admin_user.full_name.should == "Max Mustermann"
end
end
目前只有第一个管理测试失败,但如果我在管理模型中验证用户的存在,几乎所有测试都会失败。也许我的测试或工厂是错误的?