我一直在嘗試為在瀏覽器中手動作業的表單撰寫系統測驗。
我有一個Speaker模型has_one :individual。表單欄位如下所示:
<fieldset>
<%= form.label :speaker, "Who said it?" %>
<%= form.collection_select :speaker_id, Speaker.all.sort_by(&:full_name), :id, :full_name %>
</fieldset>
模型中的自定義full_name方法Speaker如下所示:
def full_name
if individual
"#{individual.first_name} #{individual.last_name}"
end
end
該if individual條件是氣味,但沒有它,我得到這個錯誤:
Minitest::UnexpectedError: ActionView::Template::Error: undefined method `first_name' for nil:NilClass
如果我添加if individual條件,則錯誤如下所示:
Minitest::UnexpectedError: ActionView::Template::Error: comparison of String with nil failed
我很困惑,因為我full_name在其他模型中使用類似的模式來對集合選擇進行排序,但這是唯一在系統測驗中引發錯誤的模式。當我在瀏覽器中手動測驗時,一切都按預期作業。
我也可以在控制臺中訪問模型中的first_name last_name和full_name方法Individual,沒問題。
這也不會導致錯誤(我可以用來:full_name在瀏覽器中顯示名稱,但它不是按字母順序排列的:
<%= form.collection_select :speaker_id, Speaker.all, :id, :full_name %>

如何在 Capybara 中修復此錯誤?或者有沒有更好的方法可以Speaker.all在按字母順序排序的 collection_select 中回傳?
更新:我通過不通過發言人模型傳遞報價/個人關系來簡化這一點。現在,我的Quote模型belongs_to :individual和Individual has_many :quotes. 這也適用于瀏覽器,但我的系統測驗遇到了同樣的錯誤:
<ActionView::Template::Error: undefined method `full_name' for nil:NilClass>
這是因此錯誤而失敗的測驗之一...
require "application_system_test_case"
class QuotesTest < ApplicationSystemTestCase
setup do
@contributor = users(:contributor)
@contributor_quote = quotes(:contributor_quote)
@category = categories(:rock_and_roll)
@field = fields(:music)
@topic_one = topics(:recording)
@topic_two = topics(:songwriting)
@individual = individuals(:john_lennon)
@group = groups(:the_beatles)
end
test "visiting the index should be accessible to all" do
visit quotes_path
assert_text @contributor_quote.body
click_on @contributor_quote.body
assert_current_path quote_path(@contributor_quote)
end
end
我的Individual模型中有這個方法:
def full_name
"#{first_name} #{last_name}"
end
這是導致失敗的視圖部分:
Speaker: <%= @quote.individual.full_name %>
如果我包括save_and_open_page錯誤看起來像這樣......

我嘗試.strip按照托馬斯的回答建議添加,但這無濟于事。
同樣,唯一的問題是這個系統測驗。它在瀏覽器中運行良好。
uj5u.com熱心網友回復:
在沒有實際看到任何測驗代碼的情況下,無法確定錯誤的來源,而且我不知道 Capybara 在哪里適合這一點。我猜你所擁有的是一個 Speaker 模型,它似乎依賴于它的individual關聯,但這實際上并沒有在任何地方強制執行,所以當你在沒有關聯個體的測驗中創建揚聲器實體時,它不會被標記為無效. 如果 Speaker 應該支持沒有關聯,individual那么您的問題是您的full_name方法在需要字串時回傳 nil。要解決這個問題,你可以做
def full_name
"#{individual&.first_name} #{individual&.last_name}".strip
end
individual存在時給你全名,不存在時給你一個空字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406643.html
標籤:
