
Plaza Model 생성rails g model plaza postitable:references{polymorphic} visible:booleanPlaza Model DB 생성rake db:migraterake db:test:clone
models/plaza.rb
belongs_to :postitable, polymorphic: true
models/post.rb
has_one :plaza, :as => :postitable, :dependent => :destroy
models/question.rb
has_one :plaza, :as => :postitable, :dependent => :destroy
...
models/###.rbhas_one :plaza, :as => :postitable, :dependent => :destroy
Plaza Factory 추가 - 다른 모델과의 관계 선언 및 객체 타입별 생성factory :post_plaza, class: "plaza" do association :postitable, :factory => :post postitable_type 'post' visible false endPost Factory 변경- Post 객체 생성시 Plaza 객체 추가after(:create) do |post| post.plaza = FactoryGirl.create(:post_plaza, postitable_id: post.id, postitable_type: "post") end
Post, Question 생성시 자동으로 생성되는 Plaza 확인describe Plaza dodescribe "모델 객체의 생성" do it "> Post 객체를 유효한 데이터로 생성시 Plaza에 추가된다." do post = create(:post) expect(post.plaza).to be_valid end... endend


app/models/post.rb
after_create :set_plaza_post
def set_plaza_post
self.create_plaza
end
it "> Post 생성시 hit의 기본값은 0이다." do
expect(build(:post).hit).to eq(0)
end
$ rails g migration add_column_to_post published_at:datetime hit:integer
db/migrate/add_column_to_post.rb
add_column :posts, :hit, :integer, default: 0
Post Model DB Column 업데이트
$ rake db:migrate
$ rake db:test:clone
it "> published가 false일때 published_at은 nil이다." do
post = create(:post, published: false)
expect(post.published_at).to be_nil
end
it "> published가 true일때 published_at에 Time이 입력된다." do
post = create(:post, published: true)
expect(post.published_at).to be_a_kind_of(Time)
end
before_save :set_published_atprivatedef set_published_at if (published == true || published == "true" || published == "1") && published_at.nil? self.published_at = Time.now elsif (published != true && published != "true" && published != "1") && published_at self.published_at = nil end end
it "> Title이 3글자 이상 255글자 이하이어야 한다." do should ensure_length_of(:title).is_at_least(3).is_at_most(255) endit "> Content가 0글자 이상 10000글자 이하이어야 한다." do should ensure_length_of(:content).is_at_least(0).is_at_most(10000) end
validates :title, presence: true, :length => { :minimum => 3, :maximum => 255 }
validates :content, presence: true, :length => { :minimum => 0, :maximum => 10000 }