【问题标题】:Tests fail with record creation in Rails 5在 Rails 5 中创建记录时测试失败
【发布时间】:2017-05-06 09:58:19
【问题描述】:

我正在学校构建一个应用程序,我遇到了这个错误。截至目前,应用程序遍历是在 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

【问题讨论】:

  • 检查你的test.log文件;由于某种原因,该记录没有存储到数据库中,如果不检查日志,就不可能确切地说出原因。

标签: ruby ruby-on-rails-5 rspec-rails


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多