Creating permalinks (slugs) in Rails - why doesn't my test work?

I am writing a small CMS as a Rails test project (I also plan to use it for my personal site). I want SEO-friendly URLs, so I have a test to check that permalinks are automatically generated based on the page title (e.g. About Us => about-us). However, I cannot understand why this test fails. Here is the code (I am using Rails 2.3.2):

# page_test.rb # note I am using the "shoulda" framework require 'test_helper' class PageTest < ActiveSupport::TestCase should_validate_presence_of :title, :permalink, :content should_validate_uniqueness_of :title should "create permalink automatically" do p = pages(:sample_page) p.save assert_equal "sample-page", p.permalink end end # pages.yml sample_page: title: Sample Page permalink: # gets automatically created by model content: This is a sample page # page.rb class Page < ActiveRecord::Base validates_presence_of :title, :permalink, :content validates_uniqueness_of :title before_save :generate_permalink private def generate_permalink self.permalink = self.title.parameterize end end 

What happens is that the permalink is zero, not the example page, as it should be. It works, however, if I manually put a permalink in the device and change the test around, for example:

 p - pages(:sample_page) p.title = "Contact Us" p.save assert_equal "contact-us", p.permalink 

I could fix this, but I wonder why it does not run the before_save method for the original test.

+4
source share
2 answers

Well, I was able to figure it out. I needed to use before_validation as a callback, not before_save

+2
source

Does it work if you remove the empty permalink: key from your pages.yml file?

0
source

All Articles