Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 如何在RSpec中测试参数计数?_Ruby On Rails 3_Testing_Exception Handling_Rspec2 - Fatal编程技术网

Ruby on rails 3 如何在RSpec中测试参数计数?

Ruby on rails 3 如何在RSpec中测试参数计数?,ruby-on-rails-3,testing,exception-handling,rspec2,Ruby On Rails 3,Testing,Exception Handling,Rspec2,如何测试一个给定的helper方法只接受一个参数 我想这样做: describe "#textile" do it "should take only one argument" do textile().should raise_error end end 但这似乎仍然打破了测试,错误是1的参数数量为0,无论您为什么要测试它,这里有一种编写方法: describe "#textile" do it "should fail when given no arguments"

如何测试一个给定的helper方法只接受一个参数

我想这样做:

describe "#textile" do
  it "should take only one argument" do
    textile().should raise_error
  end
end

但这似乎仍然打破了测试,错误是1的参数数量为0,无论您为什么要测试它,这里有一种编写方法:

describe "#textile" do
  it "should fail when given no arguments" do
    expect { textile() }.to raise_error ArgumentError
  end

  it "should accept one argument" do
    expect { textile("foo") }.not_to raise_error ArgumentError
  end
end

请注意,您可以省略
ArgumentError
,只说这些调用应该或不应该引发错误,但通过明确地说它们应该或不应该引发ArgumentError,您正在隔离您试图指定的情况<代码>织物(“foo”)可能会引发其他类型的异常,但仍会通过第二个示例。

实际上,您可以直接测试算术

>> method(:hello).arity
=> 2
您可以根据给定的默认值以及任何
*args
获得不同的答案

您将希望了解以下内容:

返回方法接受的参数数的指示。 对于采用固定数量的值的方法,返回一个非负整数 论据。对于接受可变数量参数的Ruby方法, 返回-n-1,其中n是所需参数的数目。方法 用C编写,如果调用采用可变的 争论


因此,在rspec中,您应该相应地编写测试,测试算术,而不是测试它是否会引发错误。

为什么要测试它?在任何情况下,如果您使用有效的单个参数测试它,并更改其定义以获取更多参数,那么测试将失败。除非给第二个参数一个默认值。