我的控制器中有一个方法,取消保留,调用find_ticket
方法,如果找到了票证,则在票证上调用unreserve
。
def unreserve
if find_ticket
@ticket.unreserve current_or_guest_user
render json: @ticket.show.tickets_as_json(current_or_guest_user)
else
render json: nil
end
end
private
def find_ticket
@ticket = Ticket.find params[:id]
rescue ActiveRecord::RecordNotFound
false
else
true
end
由于我已经测试了unreserve
,我只想确保调用该方法。所以当我尝试运行这个规范时:
describe 'unreserving a ticket' do
before :each do
sign_in customer
put :reserve, id: ticket_1.id
put :unreserve, id: ticket_1.id
end
it 'calls unreserve on the ticket with the current user' do
expect(controller.instance_variable_get :@ticket).to receive(:unreserve)
end
end
我希望通过,我甚至在puts
方法中抛出unreserve
语句以确保调用该方法,并在运行测试时将其输出到控制台。
我从测试中得到的输出是:
1) TicketsController unreserving a ticket calls unreserve on the ticket with the current user
Failure/Error: expect(controller.instance_variable_get :@ticket).to receive(:unreserve)
(#<Ticket:0x007f90dd6c9600>).unreserve(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
编辑:
我尝试在操作之前调用expect语句,但仍然遇到了同样的错误。这是新的测试:
it 'calls unreserve on the ticket with the current user' do
expect(controller.instance_variable_get :@ticket).to receive(:unreserve)
sign_in customer
put :reserve, id: ticket_1.id
put :unreserve, id: ticket_1.id
end
答案 0 :(得分:0)
除非我记得错误,否则您需要在提出要求之前提出您的期望。意思是你不能使用前块(不完全是)。在您的put :unreserve
电话之后移动expect
,如下所示:
describe 'unreserving a ticket' do
before :each do
sign_in customer
put :reserve, id: ticket_1.id
end
it 'calls unreserve on the ticket with the current user' do
expect(controller.instance_variable_get :@ticket).to receive(:unreserve)
put :unreserve, id: ticket_1.id
end
end