2016-01-04 35 views
0

我的RoR 4應用程序管理一個組織表,其中幾個字段包含指向參數或用戶表的ID。這裏是描述organisation.rb如何使用ruby在rails上驗證外鍵?

# Table name: organisations 
# 
# id   :integer   not null, primary key 
# name  :string(100)  not null 
# description :text 
# address  :text 
# zip   :string(20) 
# city  :string(100) 
# state  :string(100) 
# country_id :integer 
# website  :string(100) 
# email  :string(100) 
# phone  :string(100) 
# categories :text 
# status_id :integer   default(0), not null 
# legal_id :integer   default(0), not null 
# owner_id :integer   not null 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# created_by :string(100)  not null 
# updated_by :string(100)  not null 
# session_id :string(100)  not null 
# code  :string(100) 
# 

class Organisation < ActiveRecord::Base 

### validations 
    validates :name,  presence: true, length: { minimum: 5 } 
    validates :created_by, presence: true 
    validates :updated_by, presence: true 
    validates :session_id, presence: true 
    belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"    # helps retrieving the owner name 
    validates :owner, presence: true 
    belongs_to :status, :class_name => "Parameter", :foreign_key => "status_id"  # helps retrieving the parameter 
    validates :status, presence: true 
    belongs_to :legal, :class_name => "Parameter", :foreign_key => "legal_id"  # helps retrieving the parameter 
    validates :legal, presence: true 
end 

我希望確保該模型將始終測試外鍵的存在,所以我在organisation_spec.rb寫了下面的測試:

require 'rails_helper' 

RSpec.describe Organisation, type: :model do 

    describe 'Validations' 
    context 'With existing parameters and user' do 
    FactoryGirl.build(:parameter) 
    FactoryGirl.build(:user) 
    subject {FactoryGirl.build(:organisation)} 
    it {should validate_presence_of(:name)} 
    it {should validate_length_of(:name).is_at_least(5)} 
    it {should belong_to(:status).class_name('parameter')} 
    it {should belong_to(:legal).class_name('parameter')} 
    it {should belong_to(:owner).class_name('user')} 
    it {should validate_presence_of(:created_by)} 
    it {should validate_presence_of(:updated_by)} 
    it {should validate_presence_of(:session_id)} 
    end 
end 

測試應該是在組織創建之前成功創建參數和用戶。不幸的是,運行Rspec爲每個外鍵返回相同的錯誤:

rspec ./spec/models/organisation_spec.rb:39 # Organisation With existing parameters and user should belong to status class_name => parameter 
rspec ./spec/models/organisation_spec.rb:40 # Organisation With existing parameters and user should belong to legal class_name => parameter 
rspec ./spec/models/organisation_spec.rb:41 # Organisation With existing parameters and user should belong to owner class_name => user 

如何正確指定這些外鍵測試?

感謝您的幫助

+0

我預計'class_name'要不斷的名稱,例如'用戶',而不是'用戶' – zetetic

回答