title: Rspec 3 - how to handle before_validation in model test
body: <p>In my model I have a before_validation method :</p>
  
  <pre><code>class Post &lt; ActiveRecord::Base
   before_validation :generate_url
   ...
  
   private
  
  def generate_url
     return unless self.url.blank?
     year = self.published_at.class == ActiveSupport::TimeWithZone ? self.published_at.year : DateTime.now.year
     self.url = "#{year}/#{self.title.parameterize}"
  end
  </code></pre>
  
  <p>rspec/models/post.spec.rb</p>
  
  <p>testing w rspec-rails (3.1.0) and factory_girl_rails(4.4.1), I got a spec/models/post_spec.rb to validate the Post model and a spec/factories/post.rb</p>
  
  <p>validation tests are failing because of the before_validation</p>
  
  <pre><code> Post should require title to be set
   Failure/Error: it { is_expected.to validate_presence_of(:title) }
   NoMethodError:
     undefined method `parameterize' for nil:NilClass
   # ./app/models/post.rb:69:in `generate_url'
   # ./spec/models/post_spec.rb:20:in `block (2 levels) in &lt;top (required)&gt;'
  </code></pre>
  
  <p>with a debug statement in the generate_url method, I get self as nil ... so it seems the factory post is not taken in account</p>
  
  <p>spec/models/post_spec.rb</p>
  
  <pre><code>require 'rails_helper'
  
  RSpec.describe Post, :type =&gt; :model do
    it { is_expected.to validate_presence_of(:title) }
    it { is_expected.to ensure_length_of(:title).is_at_least(5) }
    it { is_expected.to validate_presence_of(:content) }
    it { is_expected.to ensure_length_of(:content).is_at_least(10) }
    it { is_expected.to validate_presence_of(:url) }
    it { is_expected.to validate_uniqueness_of(:url) }
    it { is_expected.to validate_presence_of(:published_at) }
  end
  </code></pre>
  
  <p>spec/factories/post.rb</p>
  
  <pre><code>FactoryGirl.define do
    factory :post do
      user_id 1
      title "myTitle"
      content "myContent."
      published false
      published_at "2014-09-16 08:46:38"
    end
  end
  # note : attribute url is generated with before_validation
  </code></pre>