难以接受Rspec

时间:2014-05-09 08:38:08

标签: ruby rspec

我很难过如何比较RSpec中变量(或从方法返回)中保存的字符串。

describe "comparing strings" do 
  it "will compare with a variable" do
    a = "00001000"
    expect ( a ).to eq "00001000"
  end

  it "it will compare without a variable" do
    expect( "00001000" ).to eq "00001000" 
  end
end

导致:

comparing strings
  will compare with a variable (FAILED - 1)
  it will compare without a variable

Failures:

  1) comparing strings will compare with a variable
     Failure/Error: expect ( a ).to eq "00001000"
     NoMethodError:
       undefined method `to' for "00001000":String
     # ./run.rb:21:in `block (2 levels) in <top (required)>'

Finished in 0.00074 seconds
2 examples, 1 failure

为什么第一个例子失败了,但第二个例子失败了?

1 个答案:

答案 0 :(得分:1)

您在expect之后放置了空格,您不应该:

expect( a ).to eq '00001000'

与空间相当:

expect a.to eq '00001000'

因此to方法会调用a方法并提升NoMethodError