模型我有一個Profile
模型:測試一個Rails belongs_to的使用RSpec
class Profile < ActiveRecord::Base
belongs_to :user
def fields_needed_for_completion
[self.name, self.city]
end
def completed?
!fields_needed_for_completion.any? { |f| f.nil? || f == "" }
end
end
我試圖確定如何編寫單元測試與belongs_to
關聯的模型。特別是我不確定如何正確設置測試數據。
到目前爲止,我已經把以下內容:
describe Profile do
subject(:profile) { FactoryGirl.create(:profile) }
describe "fields_needed_for_completion" do
context "with all fields missing" do
it "returns all fields as nil" do
expect(profile.fields_needed_for_completion.all? &:blank?).to be true
end
end
end
describe "#completed?" do
#TO DO
end
end
兩個問題:
是不是蠻好用的FactoryGirl創建配置文件對象,而不是直接調用
Profile.create
?目前在工廠中沒有設置屬性(即,工廠的定義如下:factory :profile do; end
)如您所見,
User
型號在這些規格中完全沒有使用。像這樣單獨測試一個模型是否合適?即使在實踐中它屬於用戶?或者我應該以某種方式嘲笑用戶?
無關的問題,但爲什麼你在你的Profile模型中重新創建ActiveModel驗證? – sevenseacat