2014-10-09 33 views
0

我正在構建一個運行輪詢的Rails(4.1.0)應用程序。每次投票都有nn對位。這裏是我的車型:Rails模型規格傳遞,Sidekiq規格失敗

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 

我的規格爲匹配和座位通過沒有問題。在投票結束時,我需要顯示獲勝者。我正在使用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車型的規格通過的很好。我將很多測試代碼都剪掉了,所以請原諒任何不匹配的標籤,假設這不是問題!

另外,當工作人員實際在開發模式下運行時,其實並未實際更新seats.is_winner屬性。

謝謝

+0

Sidekiq woker只接受字符串參數,你確定你可以傳遞一個實例給那個woker嗎?你是否開始任何派對? – dddd1919 2014-10-09 01:46:28

+0

你是對的!我錯誤地複製了。我會更新代碼。我試圖簡化,但我介紹了一個錯誤。我認爲@ job.perform會啓動worker,對吧? – panzhuli 2014-10-09 01:59:11

+0

'@ job.perform'只是發送一個工作到sidekiq隊列,那麼你需要像[bundle exec sidekiq](http://sidekiq.org/)那樣在命令中啓動一個sidekiq worker,那麼這個工作將被執行。工作人員需要幾秒鐘才能完成,所以你可以「睡覺」等待它。 – dddd1919 2014-10-09 02:08:52

回答

0

Sidekiq與您的問題無關。你直接調用執行,所以問題是rspec和activerecord。例如,將代碼從執行方法中拉出並直接放入規範中,它仍然會失敗。

我懷疑實例是陳舊的,需要從數據庫中重新加載以獲取#perform中所做的更改。