gpt4 book ai didi

ruby-on-rails - 使用 Rspec should_receive 测试 Controller 是否正确调用对象上的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:45:09 24 4
gpt4 key购买 nike

首先,我应该说,虽然我已经阅读了很多关于 should_receive 的内容,但我仍然不完全确定我是否理解它背后的概念,所以我正在做的事情可能完全不可能。

我有以下内容:

class PlansController
def destroy
plan = plan.find_by_id(params[:id])
if plan.cancel_stripe_subscription(params[:reason])
flash[:success] = "success"
redirect_to root_path
else
#error handling
end
end
end

class Plan
def cancel_stripe_subscription(reason)
self.status = "canceled"
self.cancellation_reason = reason
if self.save
return true
else
return false
end
end

在我的 Controller 规范中,我认为测试 cancel_stripe_subscription 方法被成功调用(使用 1should_receive1),使用正确的参数和所有内容,以及另一个测试输出是有意义的destroy 操作是正确的。

换句话说,我想编写以下 Controller 规范:

describe PlansController, "Destroy Action" do
before do
@plan = Plan.create(...)
end
it "should have called destroy action" do
delete :destroy,
plan: {
id: @plan.id,
reason: "something"
}
assigns(:plan).should_receive(:cancel_stripe_subscription).with(reason:"something").exactly(1).times.and_return(true)
end

it "should have called destroy action" do
delete :destroy,
plan: {
id: @plan.id,
reason: "something"
}
assigns(:plan).status.should == "canceled"
assigns(:plan).cancellation_reason.should == "something"
end
end

第二个测试通过,但第一个抛出

Failure/Error: assigns(:plan).should_receive(:cancel_stripe_subscription)
(#<Plan:0x007fe282931310>).cancel_stripe_subscription(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments

所以我真的有两个问题:

  1. 只是为了确认一下,我是否正确使用了should_receive?我什至应该为此进行测试吗?或者第二个测试是否已被普遍接受?
  2. 如果我应该对此进行测试,使用should_receive 的正确方法是什么? (请注意,expect(@plan).to have_received(:cancel_stripe_subscription) 也没有成功)

最佳答案

我认为这里的混淆部分是由于结合了两种不同的测试风格,mockist(你的第一个测试)和 classicist(你的第二个测试)。根据您喜欢的测试风格,使用其中一个很好,但是同时使用两者来测试同一段代码有点多余。

关于ruby-on-rails - 使用 Rspec should_receive 测试 Controller 是否正确调用对象上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30723593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com