【发布时间】: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