我有两个函数值,我正在尝试比较,以确保其中一个大于另一个,但我只是不知道如何在RSpec中做到这一点。一个函数是"uncompeted_tasks",另一个是"tasks.count",这两个函数都是用户模型的一部分。以下是我在RSpec中的内容。主题是User模型的一个实例,RSpec在"expect(ut).should be<=tc"行中给了我错误,"undefined local variable or method'ut'for#(NameError)"。怎么回事?
describe "uncompleted tasks should be less than or equal to total task count" do
before do
ut = subject.uncompleted_tasks
tc = subject.tasks.count
end
expect(ut).should be <= tc
end
查看此SO答案以了解更多详细信息,但基本上RSpec中的局部变量仅限于其局部范围,包括before
块。因此,before
块中定义的变量在测试中不可用。我建议使用实例变量:
describe "uncompleted tasks" do
before do
@ut = subject.uncompleted_task
@tc = subject.tasks.count
end
it "should be less than or equal to total task count" do
expect(@ut).should be <= @tc
end
end
您需要使用实例变量,并且您的期望需要位于it块内。如下所示:
describe "uncompleted tasks should be less than or equal to total task count" do
before do
@ut = subject.uncompleted_tasks
@tc = subject.tasks.count
end
it "something" do
expect(@ut).should be <= @tc
end
end