我需要找到构建模型对象的最佳方法。我继承了代码库,它不是很漂亮。
class Notification < ActiveRecord::Base
attr_accessible :author_id, :notifable_id, :notifable_type, :seen, :user_id
belongs_to :notifiable, :polymorphic => true因此,author_id和user_id是指向用户模型的隐式指针
#A user
has_many :notifications例如,可通知的多态关系允许具有可通知的类似模型。当您喜欢一个帖子时,您可以创建一个可通知的like和一个具有作者和接收者的通知(user_id)
我在为有通知的用户(即通知的接收者)创建工厂时遇到问题
factory :notification do |f|
n = FactoryGirl.generate(:number_notification)
user = create(:user)
#author_id
f.author_id user.id
f.user_id :user_dest
f.association :user, user
end
factory :notification_like, parent: :notification do |f|
f.notifiable_type "Like"
f.notifiable_id 1
end 此代码不起作用。它在user.id上抱怨,说它不存在。
我的功能测试如下所示:
let(:max) { create(:user) }
let(:notification) { create(:notification_like, :user_dest => max.id) }
let(:login_page) { HomeLoginPage.new }
let(:main_page) { MainPage.new }
scenario "login" do
notification
login_page.visit_page.login(max)
main_page
sleep(60)
end发布于 2015-01-01 12:31:37
您需要使用callbacks来使您的关联工作。
factory :notification do |f|
FactoryGirl.generate(:number_notification)
user
after(:build) do |notification|
notification.author_id = notification.user.id
notification.user_id = notification.user.id
end
endhttps://stackoverflow.com/questions/27320365
复制相似问题