我有这个型号:
class UserFriend < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
belongs_to :friend, class_name: User
validates :friend, presence: true
end
这家工厂:
FactoryGirl.define do
factory :user_friend do
association :user
association :friend, factory: :user
end
end
和这个规范:
require 'spec_helper'
describe UserFriend do
it "is invalid without a user" do
expect(build(:user_friend, user: nil)).to have(1).errors_on(:user)
end
it "is invalid without a friend" do
expect(build(:user_friend, friend: nil)).to have(1).errors_on(:friend)
end
end
这是我收到的错误消息:
rspec spec/models/user_friend_spec.rb
.F
Failures:
1) UserFriend is invalid without a friend
Failure/Error: expect(build(:user_friend, friend: nil)).to have(1).errors_on(:friend)
NoMethodError:
undefined method `attributes' for nil:NilClass
# ./spec/models/user_friend_spec.rb:14:in `block (2 levels) in <top (required)>'
Finished in 0.65806 seconds
2 examples, 1 failure
Failed examples:
rspec ./spec/models/user_friend_spec.rb:13 # UserFriend is invalid without a friend
Randomized with seed 56390
测试正在通过第一个期望(用户)正确传递但是第二个(朋友)失败
Aclaration :我没有使用HABTM关联,因为我在模型上有其他字段,我为该示例省略了。
答案 0 :(得分:2)
在你的模型中,使用类名字符串而不是类常量,如下所示:
belongs_to :friend, class_name: 'User'