Reputation: 61
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)>'
Upvotes: 1
Views: 1542
Reputation: 20125
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
create!
to make sure you notice when saving the object fails (it'll raise an exception if there's a validation error).Product
can be created with the data, you provide it.Upvotes: 0
Reputation: 44675
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
Upvotes: 1