如果ended_at
小於今天,我做了一個調用方法的工作。出於某種原因,即使我正在拋出一個綁定撬,它即將中斷並手動調用該方法,並且工作正常,我仍然會收到失敗。但是,如果我只是讓規範測試自行運行,我仍然會失敗。Rspec:測試是否在作業內的對象上調用方法?
我的工作:
class RemoveOldEventsFromAlgoliaJob < ApplicationJob
queue_as :default
def perform
old_events = Event.where("ended_at < ?", Date.today)
old_events.each do |e|
e.remove_from_algolia
end
end
end
我的方法:
def remove_from_algolia
index = Algolia::Index.new(@@ALGOLIA_INDEX_NAME)
index.delete_object(self.id)
end
我的規格測試:
require 'rails_helper'
RSpec.describe RemoveOldEventsFromAlgoliaJob, type: :job do
it "will remove old events from the index" do
ActiveJob::Base.queue_adapter = :test
event = FactoryGirl.create(:event, title: "EXPIRED EVENT", ended_at: 1.day.ago)
RemoveOldEventsFromAlgoliaJob.perform_now
expect(event).to receive(:remove_from_algolia)
end
end
RSpec的輸出:
Failures:
1) d will remove old events from the index
Failure/Error: expect(event).to receive(:remove_from_algolia)
(#<Event id: 401, uuid: "6e9a6f08-c34d-45af-9f3c-870b28643809", organization_id: nil, event_type_id: nil, name: "cool-event", title: "Cool Event", description: "Rad thing that's gonna happen", platform_type: "ee", platform_id: "12345678", platform_url: "http://event.com/12345678", featured: false, capacity: 100, rsvp_count: nil, attendee_count: nil, status: "upcoming", started_at: "2017-10-21 03:00:39", ended_at: "2017-03-23 07:00:00", deleted_at: "2017-10-21 03:00:39", created_at: "2017-03-24 00:24:54", updated_at: "2017-03-24 00:24:54", location_line_1: nil, location_line_2: nil, location_city: nil, location_state: nil, location_zip: nil, location_country: nil>).remove_from_algolia(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./spec/jobs/remove_old_events_from_algolia_job_spec.rb:10:in `block (2 levels) in <top (required)>'
Finished in 0.8828 seconds (files took 7.12 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/jobs/remove_old_events_from_algolia_job_spec.rb:4 # RemoveOldEventsFromAlgoliaJob will remove old events from the index
Coverage report generated for RSpec to /workproject/coverage. 384/496 LOC (77.42%) covered.
我可以規範測試過程中投入了binding.pry
我的工作中,並調用該方法成功:
4: def perform
5:
6: old_events = Event.where("ended_at < ?", Date.today)
7: old_events.each do |e|
=> 8: binding.pry
9: e.remove_from_algolia
10: end
11: end
[1] pry(#<RemoveOldEventsFromAlgoliaJob>)> e.remove_from_algolia
=> {"deletedAt"=>"2017-03-24T00:37:53.743Z", "taskID"=>206043962, "objectID"=>"409"}
[2] pry(#<RemoveOldEventsFromAlgoliaJob>)>
當你調用的方法手動,測試通過還是失敗? – emaillenin
手動調用它然後退出'pry',它仍然失敗。然而,我知道我正處在我打算成爲的環路中,所以我不知道爲什麼我不通過。我會假設它的工作原理,但測試本身已被破壞。我雖然這是測試一個方法是否在對象上調用的正確方法。 – Antonio