Home Ask Login Register

Developers Planet

Your answer is one click away!

user3809888 February 2016

Testing a Rails belongs_to model with Rspec

I have a Profile model:

class Profile < ActiveRecord::Base
  belongs_to :user

  def fields_needed_for_completion
    [self.name, self.city]

  def completed?
    !fields_needed_for_completion.any? { |f| f.nil? || f == "" }

I am trying to determine how to write unit tests for a model with a belongs_to association. In particular I'm not sure how to properly setup data for the tests.

So far, I've put together the following:

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

  describe "#completed?" do
    #TO DO

Two questions:

  1. Is it fine to use FactoryGirl to create the Profile object instead of calling Profile.create directly? There are no attributes set in the factory right now (i.e., the factory is defined like so: factory :profile do; end)

  2. As you can see, the User model is not used at all in these specs. Is it appropriate to unit test a model in isolation like this, even though in practice it will belong to a user? Or should I somehow mock out the User?


Dani February 2016

Here's how I see it:

  1. Yes, it is fine, in fact - you're using FactoryGirl exactly as it is intended. Creating your test objects through factories (as opposed to explicitly calling Model.create) allows you to reuse creation logic between multiple tests and have all creation related logic in one place. This means, for example, that if you'll add new a mandatory (one with validations) column to your model, then you'll have to adjust only the factory of that model instead of fixing numerous Model.create occurrences throughout your tests.

  2. Your second question is methodological and not a technical so it's much more open to interpetation, but here's my two cents: I think it makes sense to test the Profile model both in isolation and in relation with the User. Non user related logic can be tested in isolation and user related logic can be tested in that context. Note that FactoryGirl allows you to set up this context quite easily by defining a User association in you Profile factory.

Post Status

Asked in February 2016
Viewed 1,324 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life