我相信我的问题很容易解决。但是,我找不到如何或在哪里解决它。目前,我正在尝试在我的用户模型上测试#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
未保存,因为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
@spickermann指出的那样。有问题的实际父母是@user
而不是@other_user
。因为我只是building
用户,所以它返回了一个未保存的对象。因此不允许我们在尚未保存的对象上创建active_relationship
。将build
更改为create
已解决此问题。
感谢Spickermann和Ben Y的参与