저는 작은 CMS를 Rails 테스트 프로젝트로 작성하고 있습니다 (내 개인 웹 사이트에서도 사용할 계획 임). 나는 SEO 친화적 인 URL을 원하므로 permalinks가 페이지의 제목 (예 : About Us => about-us)을 기반으로 자동 생성되는지 확인하는 테스트가 있습니다. 그러나이 테스트가 실패한 이유를 알 수는 없습니다.Rails에서 영구 링크 (slug) 생성 - 왜 내 테스트가 실패합니까?
# 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
무엇 발생하는 영구 링크가 대신 있어야 할 것처럼 "샘플 페이지"의, 전무하다는 것이다 : 여기에 (내가 레일 2.3.2를 사용하고 있습니다) 코드입니다. 내가 예를 들어, 수동으로 고정에 영구 링크를 넣어 주변의 테스트를 변경하는 경우 그것은, 그러나, 작동 :
p - pages(:sample_page)
p.title = "Contact Us"
p.save
assert_equal "contact-us", p.permalink
는이 같은 문제를 해결할 수 있지만, 나는 왜에 대한 before_save 방법을 발사 아니에요 궁금하네요 원래 테스트.
아니요, 같은 오류입니다. "sample-page"가 필요하지만 nil을 얻습니다. –
테스트를 실행할 때 샘플 페이지가 테스트 데이터베이스에 저장됩니까? –
흠 좋습니다. 나는 문제를 보았다고 생각합니다. 영구 링크가 비어있어 저장하지 않습니다 (저장하도록 변경되었습니다! 오류가 발생했습니다). 그러나 before_save 메서드는이를 해결해야합니다. before_save가 실제로 저장하기 전에 호출되지 않는 이유가 확실하지 않습니다. –