jeudi 25 août 2016

Factory girl after_initialize

I have two ActiveRecord models User and posts. This is my user model.

class User < ActiveRecord::Base
  has_many :posts

end

and this is my Post model.

class Post < ActiveRecord::Base
  belongs_to :user
  after_initialize :set_name


  private
  def set_name
    self.name = "Post #{self.user.posts.count + 1}"
  end

end

all this is working fine but when I write my factories

FactoryGirl.define do
  factory :post do
    content 'blah blah'
    user
  end
  factory :user do
    name 'Dummy name'
  end

end

and this is my post_spec.rb file

require 'rails_helper'

RSpec.describe Post do
  context 'with valid values' do
    it 'should be valid' do
      expect(build(:post)).to be_valid
    end
  end
end

and my test case fails saying that

undefined method posts for nil class in set_name

I don't know where I'm going wrong.

Aucun commentaire:

Enregistrer un commentaire