我正在嘗試測驗我的表單行為,但是當我單擊保存時,回呼會引發如下錯誤。如果我評論下面的代碼一切正常。在這里我不想測驗回呼,但它阻止我成功測驗行為。
我能做些什么來解決這個問題。
#before_create :assign_depth
#before_save :assign_depth
喜歡.yml | 夾具
first:
name: At vero eos et accusamus
explanation: some explanation
parent:
second:
name: laborum et dolorum fuga. Et
explanation: some explanation
parent: first
喜歡.rb模型
class Fond < ApplicationRecord
...
before_create :assign_depth
before_save :assign_depth
belongs_to :parent, class_name: "Fond", optional: true
has_many :children, class_name: "Fond", foreign_key: "parent_id", dependent: :nullify
private
def assign_depth
self.depth = (self.parent.present? ? parent.depth 1 : 0)
end
end
測驗
require "application_system_test_case"
class FondsTest < ApplicationSystemTestCase
setup do
login_as users(:admin)
@fond_related = fonds(:second)
end
test "should create related fond" do
visit fonds_url
click_on "New fond"
fill_in "Name", with: "Test Test Test"
fill_in "Explanation", with: @fond_related.explanation
first(:xpath, "/html/body/div[2]/div[2]/form/div[3]/div").click()
find('div.item', text: @fond_related.name).click()
click_on ("Fond Kaydet")
assert_text "Fond was successfully created"
end
end
測驗結果
E
Error:
FondsTest#test_should_create_related_fond:
NoMethodError: undefined method ` ' for nil:NilClass
app/models/fond.rb:29:in `assign_depth'
app/controllers/fonds_controller.rb:29:in `block in create'
app/controllers/fonds_controller.rb:28:in `create'
uj5u.com熱心網友回復:
在回呼中,您正在檢查是否parent存在,但是是parent.depth壞的。系統測驗是一個完整的堆疊測驗,這里沒有跳過(如果我是這里的管理員,我現在正在查看錯誤 500)。nilnil 1
您的測驗正在做它應該做的事情,檢查行為并發現錯誤。您已成功找到一個。您應該depth在資料庫中將默認設定為 0,null: false因此它永遠不會回傳 nil。遷移應如下所示:
def change
create_table :fonds do |t|
t.integer :depth, default: 0, null: false
end
end
更改現有列
def change
change_column_default(:fonds, :depth, from: nil, to: 0)
change_column_null(:fonds, :depth, false)
end
任何低于此值的內容都意味著您每次想要操作它時都必須檢查深度。您還應該在Fond模型中進行驗證
validates :depth, presence: true, numericality: true
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464890.html
