简体   繁体   中英

Tests fail with record creation in Rails 5

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 a User . Because of this, you need to create a user in your test setup, or the validation will fail:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM