class ProductTest < ActiveSupport::TestCase
test "product attributes must not be empty" do
product = Product.new
assert product.invalid?
assert product.errors[:title].any?
assert product.errors[:description].any?
assert product.errors[:price].any?
assert product.errors[:image_url].any?
end
end
大家好。我對Ruby on Rails很新,我正在嘗試創建一個簡單的在線書店。我有一個需要測試的產品模型。我試圖用「英語」來理解這段代碼,但我很困惑。那麼,模型需要包含:title,:description,:price,:image_url是否正確?如何解釋此驗證測試代碼?
我們是否試圖測試產品模型中是否存在所有這些屬性?
謝謝大家。
「我們是否試圖測試產品模型中是否存在所有這些屬性?」是的,如果產品沒有這些屬性,並且它應該包含由這些屬性的驗證失敗導致的錯誤消息,那麼您正在測試該產品是無效的,但是我需要'product = Product.new'後面的'product.save' – bjhaid
嗨bjhaid。感謝你的快速回復。你能否澄清「product.save」部分?我想它也會測試看看保存的產品是否包含給定的屬性?謝謝。 –
觸發驗證 – bjhaid