【发布时间】:2015-10-14 17:49:16
【问题描述】:
我确定这是一个“duh”新手类型的问题,但我已经研究了好几天了,无法弄清楚为什么我的代码没有正确设置数据库中的关系。我有一个简单的 belongs_to两个模型之间的关系。
class Pod < ActiveRecord::Base
belongs_to :instigator, :class_name => “User"
attr_accessor :instigator, :instigator_id, :title
validates_presence_of :instigator, :title
validates_associated :instigator
end
和
class User < ActiveRecord::Base
has_many :instigated_pods, inverse_of: :instigator, :class_name => "Pod", as: "instigator"
end
然后我想用 rspec 和 Factory Girl 来测试它们(我认为)又是非常简单的工厂
FactoryGirl.define do
factory :pod do
title "Test pod"
instigator
end
factory :user, aliases: [:instigator] do
username
end
end
使用此设置,大多数测试都通过了,但我的 PodsController 更新测试一直失败,我终于找到了一个说明原因的测试。
require 'rails_helper'
RSpec.describe Pod, type: :model do
it "saves the relationship to the database" do
pod = FactoryGirl.create(:pod)
expect(pod.save).to be_truthy
expect(pod.reload.instigator).to_not be_nil # passes - cached?
pod_from_database = Pod.find(pod.id)
expect(pod_from_database.instigator).to_not be_nil # <- fails
end
end
似乎有什么东西阻止了在数据库中设置 pod.instigator_id,所以关系没有持久化。我也不知道为什么!!!
我尝试设置 validates_presence_of :instigator_id,但这使得大多数标准 rspec 测试失败,我从 the Rails Guides 看到了这一点:
如果您想确定是否存在关联,则需要进行测试 关联对象本身是否存在,而不是使用的外键 映射关联。
class LineItem < ActiveRecord::Base belongs_to :order validates :order, presence: true end为了验证需要存在的关联记录,您必须 为关联指定
:inverse_of选项:class Order < ActiveRecord::Base has_many :line_items, inverse_of: :order end
如有任何帮助,我们将不胜感激!
【问题讨论】:
标签: ruby-on-rails activerecord rspec associations factory-bot