做TDD
我在創建一本書并為它分配兩個作者時遇到了問題。創作失敗。它說有一個 AssociationTypeMismatch: Author(#15100) expected, got nil 這是 NilClass(#40 的一個實體。我想“作者:[]”的格式沒有被某些東西很好地閱讀。
這是測驗:
def test_has_many_and_belongs_to_mapping
apress = Publisher.find_by(name: 'Apress')
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
# apress.books << book
# apress.reload
# book.reload
# assert_equal 3, apress.books.size
# assert_equal 'Apress', book.publisher.name
end
這是錯誤:

我的 ERD:

我的架構:

uj5u.com熱心網友回復:
我認為您缺少的是setup在此測驗運行之前所需的有意義的資料。盡管這些出版商和書籍可能存在于您的開發環境/資料庫中,但測驗套件通常配置為在運行之間清除資料庫。
如果您定義了固定裝置,那么您可以像這樣參考它們:
測驗/夾具/publishers.yml
apress:
id: 1
name: Apress
測驗/夾具/authors.yml
hellsten:
id: 1
first_name: Christian
last_name: Hellsten
laine:
id: 2
first_name: Jarkko
last_name: Laine
測驗/夾具/books.yml
beginning_ruby:
title: Beginning Ruby
publisher_id: 1
ruby_recipes:
title: Ruby Recipes
publisher_id: 1
這樣測驗看起來更像這樣:
def test_has_many_and_belongs_to_mapping
apress = publishers(:apress)
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
apress.books << book
apress.reload
book.reload
assert_equal 3, apress.books.size
assert_equal 'Apress', book.publisher.name
end
或者,您可以在測驗之前創建內容,而不是使用固定裝置:
這樣測驗看起來更像這樣:
setup do
publisher = Publisher.create!(name: 'Apress')
publisher.books.create!(title: 'Beginning Ruby')
publisher.books.create!(title: 'Ruby Recipes')
Author.create!(first_name: 'Christian', last_name: 'Hellsten')
Author.create!(first_name: 'Jarkko', last_name: 'Laine')
end
def test_has_many_and_belongs_to_mapping
apress = Publisher.find_by(name: 'Apress')
assert_equal 2, apress.books.size
book = Book.new(
title: 'Rails E-Commerce 3nd Edition',
authors: [
Author.find_by(first_name: 'Christian', last_name: 'Hellsten'),
Author.find_by(first_name: 'Jarkko', last_name: 'Laine')
],
published_at: Time.now,
isbn: '123-123-123-x',
blurb: 'E-Commerce on Rails',
page_count: 300,
price: 30.5
)
apress.books << book
apress.reload
book.reload
assert_equal 3, apress.books.size
assert_equal 'Apress', book.publisher.name
end
這樣你的資料庫就有了這些值,你的find_by()呼叫應該回傳資料,而不是nil.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/437159.html
標籤:轨道上的红宝石 PostgreSQL tdd 协会 小测试
