2012-01-11 90 views
11

我在使用RSpec 2.8传递这个简单测试时遇到了问题。有参数的方法RSpec测试ArgumentError

我想写一个简单的测试,在需要它们的方法上缺少参数(即ArgumentError:错误的参数数量('x'代表'y'))。

我的测试是测试宝石组件的方法,像这样:

describe "#ip_lookup" do 
    it "should raise an ArgumentError error if no parameters passed" do 
    expect(@geolocater.ip_lookup).to raise_error(ArgumentError) 
    end 
end 

我的宝石模块的代码如下所示:

module Geolocater 
    def ip_lookup(ip_address) 
    return ip_address 
    end 
end 

我的规格与此输出运行。

Failure/Error: expect(@geolocater.ip_lookup).to raise_error(ArgumentError) 
    ArgumentError: 
     wrong number of arguments (0 for 1) 
    # ./lib/geolocater.rb:4:in `ip_lookup' 
    # ./spec/geolocater_spec.rb:28:in `block (3 levels) in <top (required)>' 

我在这里错过了什么?

回答

23

你需要一个块传递给#expect,不是正规的说法:

describe "#ip_lookup" do 
    it "should raise an ArgumentError error if no parameters passed" do 
    expect { @geolocater.ip_lookup }.to raise_error(ArgumentError) 
    end 
end 
+0

谢谢!这很好! – thoughtpunch 2012-01-11 16:15:17

+0

谢谢! 2013年仍然很棒。 – 2013-08-07 00:52:01

+0

也在2014年;) – macsig 2014-01-01 09:07:23