首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试失败,并在Rails 5中创建记录

测试失败,并在Rails 5中创建记录
EN

Stack Overflow用户
提问于 2016-12-21 12:11:08
回答 1查看 122关注 0票数 1

我正在学校构建一个应用程序,我遇到了这个错误。目前,应用遍历是在rails 4.2.6中启动的,而我运行的是5.0.0.1。

错误是:

代码语言:javascript
复制
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

我的代码如下。我已经与演练中的repo进行了比较,它与之完美匹配。我遗漏了什么?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2016-12-21 18:02:47

Rails 5与Rails 4的不同之处在于,当你有一个belongs_to关系时,Rails 5将验证相关的对象,即使你没有添加任何automatically validate the presence

可能您的Post模型属于某个User。因此,您需要在测试设置中创建一个用户,否则验证将失败:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41254959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档