2016-11-03 6 views
0

ActivityJobという名前のジョブがあり、ユーザーのgithub公開アクティビティを取得しています。minitestで無限ループをテストします

class ActivityJob < ActiveJob::Base 
    queue_as :git 

    def perform(user) 
    begin 
     #fetch github activities for a user using user's auth_token 
     activities = ActivitiesFetcher.new(user).fetch 
     # process the retrieved activities. 
    rescue Github::Error::NotFound 
     #user is not present. ignore and complete the job. 
    rescue Github::Error::Unauthorized 
     #auth token is invalid. re-assign a new token on next sign in 
     user.auth_token = nil                          
     user.save 
     # refresh_gh_client gets a new client using a random user's auth_token 
     user.refresh_gh_client 
     retry 
    rescue Github::Error::Forbidden 
     # Probably hit the Rate-limit, use another token                   
     user.refresh_gh_client                          
     retry 
    end 
    end 
end 

方法refresh_gh_clientは、DBからランダムなユーザーを取得し、新しいgh_clientを作成するために、そのauth_tokenを使用しています。新しいgh_clientが現在のユーザーに割り当てられます。これはうまくいきます。テストケースでは、メソッド呼び出しをスタブするためにモカを使用しています。

class ActivityJobTest < ActiveJob::TestCase                      
    def setup                              
    super                               
    @user = create :user, github_handle: 'prasadsurase', auth_token: 'somerandomtoken'            
    @round = create :round, :open                         
    clear_enqueued_jobs                           
    clear_performed_jobs                           
    assert_no_performed_jobs                          
    assert_no_enqueued_jobs 
    end 

    test 'perform with Github::Error::Unauthorized exception' do                  
    User.any_instance.expects(:refresh_gh_client).returns(nil) 
    ActivitiesFetcher.any_instance.expects(:fetch).raises(Github::Error::Unauthorized, {})      
    ActivityJob.perform_now(@user, 'all', @round)                     
    @user.reload                             
    assert_nil @user.auth_token                         
    end 
end 

問題は、ジョブの「再試行」はそれが一度だけ呼ばれるようになっていたという期待を壊すActivitiesFetcherを呼び出すことです。

: 
unexpected invocation: #<AnyInstance:User>.refresh_gh_client() 
unsatisfied expectations: 
- expected exactly once, invoked twice: # <AnyInstance:User>.refresh_gh_client(any_parameters) 
- expected exactly once, invoked twice: #<AnyInstance:ActivitiesFetcher>.fetch 

答えて

1

必要なActivitiesFetcherビヘイビアのインターフェイスを作成します。あなたは、テストの特異性を扱うテストのためにのみ使用されるインターフェイスの実装を作成します。