Search code examples
ruby-on-railsrspecfactory-botdestroy

delete an object in rspec rails


I want to create an object and then delete it during an rspec test... is this possible?

This code:

describe User do

  it "should be invalid if email is not unique" do
    user = FactoryGirl.create(:user, id: 1, email: "g@g.com").should be_valid
    FactoryGirl.build(:user, email: "g@g.com").should_not be_valid
    User.destroy(user.id)
    FactoryGirl.build(:user, email: "g@g.com").should be_valid
  end


end

returns the error:

Failure/Error: User.destroy(user.id)
     NoMethodError:
       undefined method `id' for true:TrueClass

Solution

  • The issue isn't that you can't delete the user within your rspec test - it's that your user object isn't getting the assignment you intended:

    FactoryGirl.create(:user, id: 1, email: "g@g.com").should be_valid
    

    evaluates to true, and is assigned to user. Then, when you try to call user.id, it looks for the id property of true and gets stuck.

    You might split out that particular line to:

    FactoryGirl.build(:user, id: 1, email: "g@g.com").should be_valid
    user = FactoryGirl.create(:user, id: 1, email: "g@g.com")
    

    or not worry about local user variable and just delete based on the email address, i.e.

    User.destroy((User.find_by email: "g@g.com").id)