【问题标题】:Rspec & FactoryGirl 'Cannot call create unless parent is saved'Rspec & FactoryGirl '除非保存父级,否则无法调用创建'
【发布时间】:2016-03-27 21:39:22
【问题描述】:

我确信我的问题很容易解决。但是,我找不到如何或在哪里解决它。目前我正在尝试在我的用户模型上测试#follow 方法。这是我的测试:

describe "#follow & #following?" do
 before(:each) do
   @other_user = FactoryGirl.create(:user)
 end

 it "returns false for user following other_user" do
   expect(@user.following?(@other_user)).to eq(false)
 end

 it "returns true for user following other_user" do
   @user.follow(@other_user)
   expect(@user.following?(@other_user)).to eq(true)
 end
end

这里是#follow 方法:

def follow(other_user)
 active_relationships.create(followed_id: other_user.id)
end

返回的错误是You cannot call create unless the parent is saved。显然这里有问题的父母是@other_user。现在第一个测试按预期通过了,因为我们显然没有像运行 #follow 方法那样运行调用 create 的方法。我的问题是如何保存这个@other_user 以便我可以创建一个active_relationship

@user 的呈现方式如下:

before { @user = FactoryGirl.build(:user) }
subject { @user }

另外,@user 正在处理所有其他测试。在@user@other_user 上运行.persisted? 时,我收到true

【问题讨论】:

  • 在规范文件中,@user 是在哪里以及如何创建的?
  • 真的是@other_user没有保存吗?我的猜测是@user 没有保存。给他们两个打电话persisted? 来测试一下。此外,您可能想对它们都调用errors,也许工厂没有返回有效实例。
  • FactoryGirl.build(:user) 返回一个未保存的用户,我怀疑@user.persisted? 返回true...请在@user.follow(@other_user) 之前添加@user.save 并测试是否让您的示例通过...
  • @spickermann 所以我测试了@other_user.persisted?,然后将其更改为@user,或者我是这么认为的。我再次运行@user.persisted?,就像spickermann 指出的那样,构建返回false。实际上创建它会让它持续存在,从而保存@user的父...你一直都是对的!感谢您的帮助。如果有更好的方法来解决这个问题,我会全力以赴。

标签: ruby-on-rails ruby rspec


【解决方案1】:

@user 未保存,因为Factory.build(:user) 返回未保存的记录。只需在运行该特定示例之前更改您的规范以保存 @user

我会这样写规范:

subject(:user) { FactoryGirl.build(:user) }

describe "#follow & #following?" do
  let(:other) { FactoryGirl.create(:user) }

  it "returns false for user following other_user" do
    expect(user.following?(other)).to be_false
  end

  context "when following" do
    before do
      user.save
      user.follow(other)
    end

    it "returns true for user following other_user" do
      expect(user.following?(other)).to be_true
    end
  end
end

【讨论】:

    【解决方案2】:

    正如@spickermann 指出的那样。有问题的实际父级是@user 而不是@other_user。因为我只是 building 的用户,所以它返回了一个未保存的对象。因此不允许我们在尚未保存的对象上创建active_relationship。将build 更改为create 已解决该问题。

    感谢Spickermann 和Ben Y 的参与

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 2014-12-24
      • 2014-05-28
      相关资源
      最近更新 更多