2011-07-28 5 views
11

내가 확인 할 결과를하는 방법이있다 :반올림 문제가

result.should == [1.0,2.0,3.0] 

을하지만 오류 얻을 : 나는 라운딩에서 문제를 생각

expected: [1.0, 2.0, 3.0] 
     got: [1.0, 2.0, 3.0] (using ==) 

을, 그러나 나는 그것들을 비교하는 방법을 알지 못한다. 예를 들어 0.1의 편차가있다.

감사합니다.

RSpec::Matchers.define :be_closed_array do |expected, truth| 
    match do |actual| 
    same = 0 
    for i in 0..actual.length-1 
     same +=1 if actual[i].round(truth) == expected[i].round(truth) 
    end 
    same == actual.length 
    end 

    failure_message_for_should do |actual| 
    "expected that #{actual} would be close to #{expected}" 
    end 

    failure_message_for_should_not do |actual| 
    "expected that #{actual} would not be close to #{expected}" 
    end 

    description do 
    "be a close to #{expected}" 
    end 
end 

답변

13

가 사용 : :

.should be_close 

심지어 여기

.should be_within 

참조 http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers

+0

주셔서 감사합니다, 나는에 대해 아는 사람이 도와 주면 나는, 내 자신의 정규 표현을 썼다 이 방법들은 배열에 어떻게 적용되는지 모르겠습니다. 각 값을 반복 했습니까? 이 줄 result.should be_close ([1.0,2.0,3.0], 0.1) 때문에 작동하지 않습니다. – zolter

+1

음 ... 잘 모르겠습니다. 자신 만의 고유 한 정규 표현식을 만드는 것이 더 좋다. – apneadiving

+1

RSpec 3 이후에만 'be_within'이 구현되었으므로 : http://www.rubydoc.info/gems/rspec-expectations/3.1.0/RSpec/Matchers#be_within-instance_method vs http://www.rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers#be_close-instance_method – Raf