【问题标题】:Rspec expect(method) vs expect(method).to be_trueRspec 期望(方法)与期望(方法).to be_true
【发布时间】:2014-03-29 08:10:17
【问题描述】:

我刚刚开始使用 RSpec 和 Rails 深入研究 TDD,我发现如果我正在测试一个应该是正确的方法,那么如果我使用 expect(method) 而不是 expect,测试将起作用(方法).to be_true。

it "is true" do
  expect(subject).to be_true
  #Works the same as...
  expect(subject)
end

是否有任何理由不使用没有 .to 的期望,它会破坏测试还是无法捕获某些故障?只是想知道。

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    你没有达到你认为的目标。 expect(false) 不会失败。 expect(true) 只成功,因为没有任何东西被测试。 例如,如果您的规范具有以下内容:

    describe "something" do
      it "does something" do
        false
        puts expect(false)
        # anything that evaluates to false
      end
    end
    

    当你运行 rspec 时你会得到这样的结果:

    #<RSpec::Expectations::ExpectationTarget:0x007ff0b35a28b8\>
    .
    
    Finished in 0.00061 seconds
    1 example, 0 failures
    

    基本上你没有断言任何东西,expect(subject) 评估为 ExpectationTarget。

    【讨论】:

      【解决方案2】:

      我认为后者起作用是巧合。

      每个期望语句都以一种或另一种方式评估为真或假。

      例如

      arr = ['a', 'b', 'c']
      expect(arr).to include('a')
      

      将返回 true,因为 arr 包含 'a'

      所以在您的情况下,expect(subject)expect(subject).to be_true 在某种程度上相当于以下内容:

      bool = true
      if bool
        # Do something here
      
      if bool == true
        # Do something here
      

      长话短说,没关系,但为了便于阅读,我更喜欢expect(subject).to be_true

      【讨论】:

        猜你喜欢
        • 2016-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多