【发布时间】:2019-11-29 09:27:21
【问题描述】:
我是一名新的编码员,所以这可能很愚蠢。以下代码在我的测试套件中失败,但在 rails 控制台中执行相同的步骤会产生预期的结果:
aura_test.rb
require 'test_helper'
class AuraTest < ActiveSupport::TestCase
def setup
@champion = champions(:aura)
@aura = Aura.new description: "Lorem ipsum Aura blah", champion_id: @champion.id, stat_type_id: 1
end
test "should be valid" do
assert @aura.valid?
end
end
aura.rb
class Aura < ApplicationRecord
belongs_to :champion, optional: true
belongs_to :stat_type
belongs_to :affinity, optional: true
belongs_to :location_group, optional: true
validates :description, presence: true
validates :champion_id, presence: true
end
champions.rb
class Champion < ApplicationRecord
belongs_to :faction
belongs_to :affinity
belongs_to :rarity
belongs_to :champion_type
has_one :aura, dependent: :destroy
validates :name, presence: true
end
赛程: 冠军.yml
name: AuraChamp
faction: one
affinity: one
rarity: one
champion_type: one
当我在 Rails 控制台中运行类似代码时:
>> @champion = Champion.first
Champion Load (0.1ms) SELECT "champions".* FROM "champions" ORDER BY "champions"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Champion id: 1, name: "", faction_id: 1, affinity_id: 1, rarity_id: 1, champion_type_id: 1, created_at: "2019-07-19 23:50:18", updated_at: "2019-07-19 23:50:18">
>> @aura = Aura.new description: "Lorem ipsum Aura blah", champion_id: @champion.id, stat_type_id: 1
=> #<Aura id: nil, name: nil, description: "Lorem ipsum Aura blah", champion_id: 1, stat_type_id: 1, affinity_id: nil, location_group_id: nil, increase: nil, is_percent: nil, created_at: nil, updated_at: nil>
>> @aura.valid?
StatType Load (0.1ms) SELECT "stat_types".* FROM "stat_types" WHERE "stat_types"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> true
测试运行时我得到以下结果
FAIL["test_should_be_valid", AuraTest, 0.5133701380000275]
test_should_be_valid#AuraTest (0.51s)
Expected false to be truthy.
test/models/aura_test.rb:11:in `block in <class:AuraTest>'
【问题讨论】:
-
我不太了解 rails 或它的固定装置是如何工作的,但您可以在您的
champions固定装置中添加一个id吗?或者也许命名那个夹具?它似乎与this question 有关。另外,我相信Champion.first不会和champions(:aura)一样,因为一个是从数据库中获取记录,另一个是使用你的fixture。 -
使用调试器查看您的测试中
@aura存在哪些错误,因此@aura.errors.full_messages您将得到问题的答案。
标签: ruby-on-rails automated-tests ruby-on-rails-5