두 모델 Article
및 ArticleVote
이 있습니다. 기사 투표를 취소하면 (사용자가 투표를 취소 함) 기사의 점수를 변경하고 싶습니다. 그래서 콜백했다.ActiveRecord 관련 모델 속성 변경
context '#destroy' do
let(:user) { FactoryGirl.create(:user) }
let(:article) { FactoryGirl.create(:article) }
it 'changes article score by nevative vote value' do
ArticleVote.upvote(user, article)
vote = ArticleVote.where(user: user, article: article).first
expect{ vote.destroy }.to change{ vote.article.score }.by -1
end
end
Shouldn을 :
class ArticleVote < ActiveRecord::Base
belongs_to :article
belongs_to :user
before_destroy :before_destroy
validates :value, inclusion: {in: [1, -1]}
def self.upvote(user, article)
cast_vote(user, article, 1)
end
def self.downvote(user, article)
cast_vote(user, article, -1)
end
private
def self.cast_vote(user, article, value)
vote = ArticleVote.where(user_id: user.id, article_id: article.id).first_or_initialize
vote.value = value
vote.save!
article.score += value
article.save!
end
def before_destroy
article.score -= value
article.save
end
end
내 ArticleVote#destroy
테스트가 실패 :
context '#destroy' do
let(:user) { FactoryGirl.create(:user) }
let(:article) { FactoryGirl.create(:article) }
it 'changes article score by negative vote value' do
ArticleVote.upvote(user, article)
expect{ ArticleVote.where(user: user, article: article).first.destroy }.to change{ article.score }.by -1
end
end
Failures:
1) ArticleVote voting #destroy should change article score by nevative vote value Failure/Error: expect{ ArticleVote.where(user: user, article: article).first.destroy }.to change{ article.score }.by -1 result should have been changed by -1, but was changed by 0 # ./spec/models/article_vote_spec.rb:32:in `block (4 levels) in '
나는이 내 테스트를 변경, 그것은 통과 여기처럼 내 ArticleVote 모델이 모습입니다 이 둘은 동등한가? 내 article
및 vote.article
은 과 일치해야합니까?
(모델 ... 모델) 무엇 실패 할 때 첫 번째 테스트의 출력입니까? – mralexlau
실패로 업데이트 됨 –