Stub传递参数到范围

时间:2013-05-14 09:11:46

标签: ruby ruby-on-rails-3.2 rspec2

我的模型中的范围看起来像:

scope :public, -> { another_scope.where(v_id: 1) }

当我在测试中存根这个模型时:

model.stub(:test).and_return(test)

它将值传递给此范围,因此我收到

wrong number of arguments (1 for 0)

我该如何避免这种情况? 当我将其更改为:

scope :public, ->(arg) { another_scope.where(v_id: 1) }

它工作正常,但从不使用arg

当我不使用lambda ex:

时,它也可以正常工作
scope :public, another_scope.where(v_id: 1)

1 个答案:

答案 0 :(得分:1)

使用Proc代替lambda。

scope :public, proc{ another_scope.where( v_id: 1 ) }

lambdas是一种“严格”的过程,需要适量的论据。

或者,如果你想保留'stabby lambda'语法(虽然它不那么可读,并且看起来很奇怪让我感到厌烦,就像一个微缩的索伦之眼),这里有点破解:< / p>

scope :public, ->(*){ another_scope.where( v_id: 1 ) }

splat的功能与在def foo( *args ); end等方法签名中使用它时的方式完全相同,只是args不会在变量中捕获。