[英]This code is failing test in automated testing, but works in rails console
我是新編碼員,所以這可能有點愚蠢。 下面的代碼在我的測試套件中失敗,但是在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
光環
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
固定裝置:Champions.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>'
在您的模型中:
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 //<= Notice this validation here
end
您有驗證champion_id
這意味着,直到您提供一個值的記錄將是無效的champion_id
現在查看您的燈具:
name: AuraChamp
faction: one
affinity: one
rarity: one
champion_type: one
您沒有@champion.id
在此處訪問的id
def setup
@champion = champions(:aura)
@aura = Aura.new description: "Lorem ipsum Aura blah", champion_id: @champion.id, stat_type_id: 1
end
您的Rails控制台步驟正在通過,因為當記錄保存到數據庫時,它會自動獲取唯一的ID
嘗試像這樣更改燈具:
name: AuraChamp
id: 1
faction: one
affinity: one
rarity: one
champion_type: one
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.