Ruby Rails 5中的记录创建导致测试失败
我正在学校开发一个应用程序,我遇到了这个错误。到目前为止,应用程序漫游是在rails 4.2.6中启动的,我正在运行5.0.0.1 错误是:Ruby Rails 5中的记录创建导致测试失败,ruby,ruby-on-rails-5,rspec-rails,Ruby,Ruby On Rails 5,Rspec Rails,我正在学校开发一个应用程序,我遇到了这个错误。到目前为止,应用程序漫游是在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
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
Rails 5与Rails 4的不同之处在于,当您有一个
归属
关系时,Rails 5将保留关联对象的属性,即使您不添加任何验证
您的Post
型号可能属于用户。因此,您需要在测试设置中创建一个用户,否则验证将失败:
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
Rails 5与Rails 4的不同之处在于,当您有一个归属
关系时,Rails 5将保留关联对象的属性,即使您不添加任何验证
您的Post
型号可能属于用户。因此,您需要在测试设置中创建一个用户,否则验证将失败:
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
检查您的test.log
文件;由于某种原因,记录没有存储到数据库中,如果不检查日志,就无法确切说明原因。请检查test.log
文件;由于某种原因,记录没有存储到数据库中,如果不检查日志,就无法确切说明原因。