我无法解决以下 rspec 验证错误:
Failures:
1) User treating associations should have the right treatings in the right order
Failure/Error: FactoryGirl.create(:treating, requestor: @user, created_at: 1.day.ago)
ActiveRecord::RecordInvalid:
Validation failed: Requestee can't be blank
# ./spec/models/user_spec.rb:143:in `block (3 levels) in <top (required)>'
我正在处理两个模型,用户和治疗(将其视为会议):
用户.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :sent_treatings, :foreign_key => "requestor_id", :class_name => "Treating", dependent: :destroy
has_many :received_treatings, :foreign_key => "requestee_id", :class_name => "Treating", dependent: :destroy
end
治疗.rb
class Treating < ActiveRecord::Base
attr_accessible :intro, :proposed_date, :proposed_location
validates :intro, presence: true, length: { maximum: 190 }
validates :requestor_id, presence: true
validates :requestee_id, presence: true
belongs_to :requestor, class_name: "User"
belongs_to :requestee, class_name: "User"
default_scope order: 'treatings.created_at DESC'
end
最后,我的 user_spec 中给我这个错误的部分:
describe "treating associations" do
before { @user.save }
let!(:older_treating) do
FactoryGirl.create(:treating, requestor: @user, created_at: 1.day.ago)
FactoryGirl.create(:treating, requestee: @user, created_at: 1.day.ago)
9end
let!(:newer_treating) do
FactoryGirl.create(:treating, requestor: @user, created_at: 1.hour.ago)
FactoryGirl.create(:treating, requestee: @user, created_at: 1.hour.ago)
end
it "should have the right treatings in the right order" do
@sent_treating = requestor.sent_treatings.build(intro: "Lorem ipsum")
@sent_treating.requestee = requestee
@received_treating = requestee.received_treatings.build(intro: "Lorem ipsum")
@received_treating.requestor = requestor
requestor.sent_treatings.should == [newer_treating, older_treating]
requestee.received_treatings.should == [newer_treating, older_treating]
end
我不确定为什么 'requestee' 在这里会是空白的并且可以使用一些帮助。谢谢你。
编辑:工厂在下面,谢谢!
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
factory :admin do
admin true
end
end
factory :treating do
intro "Lorem ipsum"
end
end
(我尝试在 :treating 工厂的 'intro' 下方添加 'user'、'requestor' 和 'requestee',但仍然没有成功)。当我在工厂文件中添加“用户”时(在“介绍”“Lorem ipsum”下方),我收到以下错误:
1) User treating associations should have the right treatings in the right order
Failure/Error: FactoryGirl.create(:treating, requestor: @user, created_at: 1.day.ago)
NoMethodError:
undefined method `user=' for #<Treating:0x00000104fa0668>
# ./spec/models/user_spec.rb:143:in `block (3 levels) in <top (required)>'
当我将“请求者”和“请求者”添加到工厂而不是用户(除了使用)时,我收到以下错误:
Failures:
1) User treating associations should have the right treatings in the right order
Failure/Error: FactoryGirl.create(:treating, requestor: @user, created_at: 1.day.ago)
ArgumentError:
Trait not registered: requestee