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:

  1. 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)

  2. 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:

  1. yes, fine, in fact - you're using factorygirl intended. creating test objects through factories (as opposed explicitly calling model.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 numerous model.create occurrences throughout tests.

  2. 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 relation user. non user related logic can tested in isolation , user related logic can tested in context. note factorygirl allows set context quite defining user association in profile factory.


Comments

Popular posts from this blog

Unlimited choices in BASH case statement -

Redirect to a HTTPS version using .htaccess -

javascript - jQuery: Add class depending on URL in the best way -