我有一个名为ActivityJob的工作,它获取用户的github公共活动。
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获取一个随机用户,并使用其auth_token创建一个新的gh_client。新的gh_client被分配给当前用户。这工作正常。在测试用例中,我使用mocha来存根方法调用。
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
答案 0 :(得分:1)
为您需要的ActivitiesFetcher行为创建一个界面。您创建了一个接口实现,仅用于处理测试特性的测试。