1

I am trying to test for "A product can list users that have reviewed it without duplicates"

this is what my test looks like

product_spec.rb

describe Product do

let!(:product) { Product.create } 
.
.#other test
.

  it "can list users that review it without duplicates" do
   product.reviews.create({user_id: 1, review: "test"})
  product.reviews.create({user_id: 1, review: "test2"})

   product.user.uniq.count.should eq(1)
  end
end

terminal result

1) Product can list users that review it without duplicates
 Failure/Error: product.reviews.create({user_id: 1, review: "test"})
 ActiveRecord::RecordNotSaved:
   You cannot call create unless the parent is saved
 # ./spec/models/product_spec.rb:49:in `block (2 levels) in <top (required)>'
2
  • product.save => boolean Commented Sep 11, 2013 at 12:54
  • You need to share more of your code, including anything involved in the creation of product in your test. Commented Sep 11, 2013 at 13:02

2 Answers 2

1

The problem is in this line:

product.save.reviews.create

Save returns boolean whether object has been saved successfully or not. You need to split this into two lines:

product.save
product.reviews.create
Sign up to request clarification or add additional context in comments.

1 Comment

and I suggest to use save! and create! to catch if some records can not be saved because of validation issues.
0

You are trying to create a Review on a Product that hasn't been saved with:

product.reviews.create()

I'm guessing product isn't valid, thus it hasn't been saved by

let!(:product) { Product.create } 

which simply returns the invalid object if create fails.

You should

  1. Use create! to make sure you notice when saving the object fails (it'll raise an exception if there's a validation error).
  2. Make sure your Product can be created with the data, you provide it.

2 Comments

you say : (it'll raise an exception instead of returning false), "create" don't return false if saving object fails, it return an invalid object model instead
Indeed. Corrected my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.