我设置了一个自定义验证,用于在提交评论之前检查用户是否已投票选择了相册。验证在客户端正常工作,但是当涉及到运行我的Rspec测试时,我似乎遇到了一些问题。
验证使用Acts As Votable gem的voted_for?方法。不幸的是,事情变得糟糕。对于我的非自定义验证(通常btw工作)我收到如下错误:
3) Review validations should ensure body has a length of at least 40
Failure/Error: it { should validate_length_of(:body).is_at_least(40) }
NoMethodError:
undefined method `voted_for' for nil:NilClass
为了识别此方法,我需要做什么?
审核模式
class Review < ActiveRecord::Base
belongs_to :album
belongs_to :owner, class_name: "User", foreign_key: :user_id
validates :body, presence: true, length: { minimum: 40 }
def album_vote
if !owner.voted_for?(album)
errors.add(:review, "requires an album vote before submitting")
end
end
end
审核工厂
FactoryGirl.define do
factory :review do
body { Faker::Lorem.paragraph(2) }
album
association :owner, factory: :user
end
end
答案 0 :(得分:0)
您需要确保确实存在所有者。错误只是因为你正在调用nil并且与ActsAsVotable
没有任何关系。
class Review < ActiveRecord::Base
belongs_to :album
belongs_to :owner, class_name: "User", foreign_key: :user_id
validates :body, presence: true, length: { minimum: 40 }
validates :owner, presence: true
def album_vote
# consider raising an error if there is no owner.
if owner && !owner.voted_for(album)
errors.add(:review, "requires an album vote before submitting")
end
end
end
然后更改工厂定义以创建所有者:
FactoryGirl.define do
factory :user, aliases: [:owner] do
# ...
end
end
FactoryGirl.define do
factory :review do
body { Faker::Lorem.paragraph(2) }
album
owner
end
end