2013-11-27 43 views
0

我有两个函数值,我试图比较,并确保一个比另一个大,我只是不知道如何在RSpec中做到这一点。一个函数是“uncompleted_tasks”,另一个是“tasks.count”,它们都是用户模型的一部分。这是我在RSpec中的。该主题是User模型的一个实例,RSpec向我提供了“expect(ut)。”应该是< = tc“行上的错误”未定义的局部变量或方法'ut'for#(NameError)“。这是怎么回事?Ruby on Rails RSpec比较函数值

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 

回答

0

退房this SO answer进一步的细节,但在基本的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 
0

您需要使用实例变量,并且您的期望需要位于它的块内。如下所示:

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