首页 > 解决方案 > RSpec 未通过“应该保存”测试

问题描述

链接到回购

我是测试 Rails 的新手,所以这可能是一件非常小的事情,但我不知道出了什么问题。所以我有一些我想测试的模型。现在测试很简单;如果满足所有验证,则测试属性的存在并保存。

我的模型之一是我Profile belongs_toUsers模型并通过了所有这些测试spec/models/profiles_spec.rb

require 'rails_helper'

RSpec.describe Profile, type: :model do
  context 'validation tests' do
    it 'ensures user_id presence' do
      profile = Profile.new(platform: 0, region: 0, tag: 'GamerTag', sr: 1600).save
      expect(profile).to eq(false)
    end

    it 'ensures platform presence' do
      profile = Profile.new(user_id: 1, region: 0, tag: 'GamerTag', sr: 1600).save
      expect(profile).to eq(false)
    end

    it 'ensures region presence' do
      profile = Profile.new(user_id: 1, platform: 0, tag: 'GamerTag', sr: 1600).save
      expect(profile).to eq(false)
    end

    it 'ensures tag presence' do
      profile = Profile.new(user_id: 1, platform: 0, region: 0, sr: 1600).save
      expect(profile).to eq(false)
    end

    it 'ensures sr presence' do
      profile = Profile.new(user_id: 1, platform: 0, region: 0, tag: 'GamerTag').save
      expect(profile).to eq(false)
    end

    it 'should save successfully' do
      profile = Profile.new(user_id: 1, platform: 0, region: 0, tag: 'GamerTag', sr: 1600).save
      expect(profile).to eq(true)
    end
  end
end

app/models/profile.rb

class Profile < ApplicationRecord
  validates :platform, presence: true
  validates :region, presence: true
  validates :tag, presence: true
  validates :sr, presence:true

  belongs_to :user

  enum platform: [:pc, :xbl, :psn]
  enum region: [:us, :eu]
end

但是还有我的其他模型,它们“通过”了所有属性存在验证测试,那里有问题,因为当我注释掉它们的属性验证并失败时,它们仍然通过'should save successfully'测试失败时它们仍然通过。

最令人困惑的部分?当我运行 rails 控制台并手动测试它返回预期值(true)时,就像我的Student模型一样belongs_to :profile一样。

所以我真的不知道这里发生了什么。有什么想法请扔掉。如果大家需要更多信息,请告诉我。

标签: ruby-on-railsrspec-rails

解决方案


确实,这是缺少相关记录的错误。让我们以教练规格为例:

it 'should save successfully' do
  coach = Coach.new(profile_id: 1, roles: ['tank']).save
  expect(coach).to eq(true)
end

这里(在我的实验中)没有 id=1 的配置文件。事实上,根本没有配置文件。因此,正如预期的那样,该规范失败了。

Buuuut,当我们到达配置文件规范时:

it 'should save successfully' do
  profile = Profile.new(user_id: 1, platform: 0, region: 0, tag: 'GamerTag', sr: 1600)
  expect(profile).to eq(true)
end

id=1 的用户确实存在(可能是因为用户规范在此之前运行并成功创建了用户记录)。

教训:

  1. 始终在测试之间清理/回滚数据库(或以其他方式使其原始)
  2. 始终以随机顺序运行测试。正如您在此线程中看到的那样,规范顺序依赖性可能非常难以检测。

推荐阅读