ruby-on-rails - RSpec 未通过“应该保存”测试
问题描述
我是测试 Rails 的新手,所以这可能是一件非常小的事情,但我不知道出了什么问题。所以我有一些我想测试的模型。现在测试很简单;如果满足所有验证,则测试属性的存在并保存。
我的模型之一是我Profile
belongs_to
的Users
模型并通过了所有这些测试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
一样。
所以我真的不知道这里发生了什么。有什么想法请扔掉。如果大家需要更多信息,请告诉我。
解决方案
确实,这是缺少相关记录的错误。让我们以教练规格为例:
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 的用户确实存在(可能是因为用户规范在此之前运行并成功创建了用户记录)。
教训:
- 始终在测试之间清理/回滚数据库(或以其他方式使其原始)
- 始终以随机顺序运行测试。正如您在此线程中看到的那样,规范顺序依赖性可能非常难以检测。
推荐阅读
- python - 为什么无法获得 title 属性?
- google-analytics - 如何将内容数据导入 Google Analytics?
- r - 在 dplyr 1.0.0 中运行缓慢的分组 tibble 中的 n_distinct
- python - 熊猫日期时间 index.is_quarter_end 错误
- awk - awk,为什么在代码中输入时不读取零?
- azure - Azure CDN 返回 403 禁止
- go - 具有无符号值的位移给出有符号结果
- python - 将 python 字典转换为 pandas 数据框,但这段代码不允许我这样做。(NBA 数据转义)
- laravel - 在刀片模板中保留带输出的缩进
- javascript - 为什么图像弹出然后又消失了