我正在学校建立一个应用程序,我遇到了这个错误。截至目前,应用程序遍历已在rails 4.2.6中启动,我正在运行5.0.0.1。
错误是:
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
我的代码如下。我已经比较了漫步中的回购,它完美匹配。我错过了什么?
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
答案 0 :(得分:0)
Rails 5与Rails 4的不同之处在于,当您有belongs_to
关系时,Rails 5将automatically validate the presence关联对象,即使您没有添加任何验证。
您的Post
模型可能属于User
。因此,您需要在测试设置中创建用户,否则验证将失败:
describe "Creation" do
before do
@user = User.create( ... )
@post = Post.create(date: Date.today, rationale: "Anything", user: @user)
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