I am building an app in school and I am running into this error. As of right now the app walk through was started in rails 4.2.6, and I am running 5.0.0.1.
The error is:
Failures:
1) Post Creation can be created
Failure/Error: expect(@post).to be_valid
expected #<Post id: nil, date: "2016-12-20", rationale: "Anything", created_at: nil, updated_at: nil, user_id: nil> to be valid, but got errors: User must exist
# ./spec/models/post_spec.rb:10:in `block (3 levels) in <top (required)>'
Finished in 0.65569 seconds (files took 2.19 seconds to load)
10 examples, 1 failure
Failed examples:
rspec ./spec/models/post_spec.rb:9 # Post Creation can be created
My code is as follows. I have compared to the repo on the walk-through and it matches perfectly. What am i missing?
require 'rails_helper'
RSpec.describe Post, type: :model do
describe "Creation" do
before do
@post = Post.create(date: Date.today, rationale: "Anything")
end
it "can be created" do
expect(@post).to be_valid
end
it "cannot be created without a date and rationale" do
@post.date = nil
@post.rationale = nil
expect(@post).to_not be_valid
end
end
end
Rails 5 differs from Rails 4 in that when you have a
belongs_to
relation, Rails 5 will automatically validate the presence of the associated object, even without you adding any validations.Probably your
Post
model belongs to aUser
. Because of this, you need to create a user in your test setup, or the validation will fail: