Testing a Rails belongs_to model with Rspec -
i have profile
model:
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
i trying determine how write unit tests model belongs_to
association. in particular i'm not sure how setup data tests.
so far, i've put following:
describe profile subject(:profile) { factorygirl.create(:profile) } describe "fields_needed_for_completion" context "with fields missing" "returns fields nil" expect(profile.fields_needed_for_completion.all? &:blank?).to true end end end describe "#completed?" #to end end
two questions:
is fine use factorygirl create profile object instead of calling
profile.create
directly? there no attributes set in factory right (i.e., factory defined so:factory :profile do; end
)as can see,
user
model not used @ in these specs. appropriate unit test model in isolation this, though in practice belong user? or should somehow mock out user?
here's how see it:
yes, fine, in fact - you're using
factorygirl
intended. creating test objects through factories (as opposed explicitly callingmodel.create
) allows reuse creation logic between multiple tests , have creation related logic in 1 place. means, example, if you'll add new mandatory (one validations) column model, you'll have adjust factory of model instead of fixing numerousmodel.create
occurrences throughout tests.your second question methodological , not technical it's more open interpetation, here's 2 cents: think makes sense test
profile
model both in isolation , in relationuser
. non user related logic can tested in isolation , user related logic can tested in context. notefactorygirl
allows set context quite defininguser
association inprofile
factory.
Comments
Post a Comment