Rspec & FactoryGirl "除非保存父级,否则无法调用 create"



我相信我的问题很容易解决。但是,我找不到如何或在哪里解决它。目前,我正在尝试在我的用户模型上测试#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的参与

最新更新