【问题标题】:Ruby on Rails RSpec Compare Function ValuesRuby on Rails RSpec 比较函数值
【发布时间】:2013-11-28 01:17:14
【问题描述】:

我有两个函数值,我正在尝试比较并确保一个大于另一个,但我无法弄清楚如何在 RSpec 中执行此操作。一个函数是“uncompleted_tasks”,另一个是“tasks.count”,两者都是用户模型的一部分。这是我在 RSpec 中的内容。主题是用户模型的一个实例,RSpec 在“expect(ut).should be

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    查看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
    

    【讨论】:

      【解决方案2】:

      您需要使用实例变量,并且您的期望需要在 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
      

      【讨论】:

        猜你喜欢
        • 2015-11-16
        • 1970-01-01
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多