在我的應用程序中,當用戶初始化時,我希望他們構建5個項目。我見過的測試斷言有,例如expect(@user.items.count).to eq(5)
。但是,我一直在嘗試驗證項目的長度並測試驗證本身,而不是與用戶關聯的對象的數量。這甚至有可能嗎?如果是這樣,那麼解決這個問題的最好方法是什麼?如何驗證和測試Rails 4中關聯對象的串聯創建?
以下是我到目前爲止的相關代碼。
class User < ActiveRecord::Base
ITEMS_ALLOWED = 5
has_many :items
validates :items, length: {is: ITEMS_ALLOWED}
after_initialize :init_items
def init_items
ITEMS_ALLOWED.times { items.build }
end
...
我的相關測試,使用RSpec的,法克爾和FactoryGirl
describe User do
before :each do
@user = build(:user, username: "bob")
@user.save
end
it "is invalid with more than 5 items" do
user3 = build(:user)
user3.save
expect(user3.items.create(name: "test")).not_to be_valid
end
end
目前測試嘗試驗證所創建的項目。我嘗試將驗證移至Item類,但是我收到錯誤,未定義的方法項爲零,嘗試撥打user.items.count
。
class Item < ActiveRecord::Base
belongs_to :user
validates :number_of_items, length: {is: 5}
def number_of_items
errors.add("User must have exactly 5 items.") unless user.items.count == 5
end
end
================ 更新:失敗消息時,有在項目類中沒有驗證。
Failures:
1) User initialization is invalid with more than 5 items
Failure/Error: expect(user3.items.create(name: "test")).not_to be_valid
expected #<Item id: 16, name: "test", user_id: 3, photo: nil, created_at: "2014-01-14 00:24:11", updated_at: "2014-01-14 00:24:11", photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil, description: nil> not to be valid
謝謝彼得!你將如何實現驗證?我很難搞清楚在哪裏插入它。我看到的過程是:構建用戶 - >構建項目 - >保存用戶 - >保存項目 –
其實,在看了這些之後,我認爲你應該能夠在不繞過驗證的情況下完成它,但驗證需求絕對是在用戶。如果您刪除了項目驗證,那麼您是否仍然有問題?如果是這樣,你可以發佈細節? –
將失敗消息添加到原始文章 –