我正在构建一个运行民意调查的Rails(4.1.0)应用程序。每次投票都有n
与n
席位的比赛。这是我的模特:
class Matchup < ActiveRecord::Base
has_many :seats, dependent: :destroy
def winning_seat
seats.sort { |a,b| a.number_of_votes <=> b.number_of_votes }.last
end
end
class Seat < ActiveRecord::Base
belongs_to :matchup
validates :matchup, presence: true
validates :number_of_votes, presence: true
def declare_as_winner
self.is_winner = true
self.save
end
end
我对Matchup和Seat的规格没有问题。在民意调查结束时,我需要显示获胜者。我正在使用Sidekiq工作来处理民意调查的结束。它做了很多事情,但这里有相关的代码:
class EndOfPollWorker
include Sidekiq::Worker
def perform(poll_id)
poll = Poll.where(:id poll_id)
poll.matchups.each do |matchup|
# grab the winning seat
winning_seat = matchup.winning_seat
# declare it as a winner
winning_seat.declare_as_winner
end
end
end
这名工人的规格没有通过:
require 'rails_helper'
describe 'EndOfPollWorker' do
before do
#this simple creates a matchup for each poll question and seat for every entry in the matchup
@poll = Poll.build_poll
end
context 'when the poll ends' do
before do
@winners = @poll.matchups.map { |matchup| matchup.seats.first }
@losers = @poll.matchups.map { |matchup| matchup.seats.last }
@winners.each do |seat|
seat.number_of_votes = 1
end
@poll.save!
@job = EndOfPollWorker.new
end
it 'it updates the winner of each matchup' do
@job.perform(@poll.id)
@winners.each do |seat|
expect(seat.is_winner?).to be(true)
end
end
it 'it does not update the loser of each matchup' do
@job.perform(@poll.id)
@losers.each do |seat|
expect(seat.is_winner?).to be(false)
end
end
end
end
end
end
当我运行此规范时,我得到:
EndOfPollWorker when poll ends it updates the winner of each matchup
Failure/Error: expect(seat.is_winner?).to be(true)
expected true
got false
我对Seat和Matchup模型的规格传递得很好。我删除了很多测试代码,请原谅任何不匹配的标签,假设不是问题!
此外,当工作人员实际在开发模式下运行时,seat.is_winner属性实际上并未更新。
由于
答案 0 :(得分:0)
Sidekiq与您的问题无关。您直接调用perform,因此问题出在rspec和activerecord上。例如,将代码从perform方法中拉出并直接放入规范中,它仍然应该失败。
我怀疑这些实例是陈旧的,需要从数据库中重新加载#adload以获取#perform中所做的更改。