当我试图在内部检查我的方法是否在rspec中调用时,它得到了以下错误
context "#Meeting_schedule" do
let(:meeting_schedule) { FactoryGirl.create(:meeting_schedule,:time=>"morning",:schedule_name=>"planned_meet", :schedule_info=>[{ "from"=>"00:00", "to"=>"00:01"}]) }
it "if the same schedule was created again dont save it again" do
schedule.save
params = {:time=>"morning",:schedule_name=>"planned_meet", :schedule_info=>[{ "from"=>"00:00", "to"=>"00:01"}]}
meeting_schedule.create_or_update_meeting_schedule(params)
expect(meeting_schedule).to receive(:updating_the_user)
end
end
我收到以下错误
Failure/Error: expect(meeting_schedule.create_or_update_meeting_schedule(params)).to receive(:updating_the_user)
(#<Meeting_schedule:0x0055dbaf0da710>).updating_the_user(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./spec/models/meeting_schedule_spec.rb:122:in `block (4 levels)
那么我的代码出了什么问题?
我的方法
def create_or_update_meeting_schedule(params)
self.attributes = params
if self.changed and self.save
updating_the_user
end
self
end
有人能帮我解决吗
在调用被测方法之前,必须始终设置Mocks,因为没有可靠的方法来测试Ruby中是否调用了普通方法。在RSpec中有两种方法可以做到这一点。
第一种是使用expect(...).to receive(...)
,这必须在调用该方法之前完成——这将分离该方法,并将其替换为包装原始方法的mock。
如果在示例中未调用该方法,则测试将失败。
第二种是使用间谍。你可以用间谍替换整个对象:
RSpec.describe "have_received" do
it "passes when the message has been received" do
invitation = spy('invitation')
invitation.deliver
expect(invitation).to have_received(:deliver)
end
end
这个";"间谍对象";将跟踪您调用的任何方法。
你也可以监视单一的方法:
class Invitation
def self.deliver; end
end
RSpec.describe "have_received" do
it "passes when the expectation is met" do
allow(Invitation).to receive(:deliver)
Invitation.deliver
expect(Invitation).to have_received(:deliver)
end
end
Spies在您想要在测试设置中模拟方法的情况下非常有用,例如在before
块中。
class Invitation
def self.deliver; end
end
RSpec.describe "have_received" do
before do
allow(Invitation).to receive(:deliver)
end
it "passes when the expectation is met" do
Invitation.deliver
expect(Invitation).to have_received(:deliver)
end
end