Ruby on rails 测试是否调用了控制器中的方法

Ruby on rails 测试是否调用了控制器中的方法,ruby-on-rails,rspec,Ruby On Rails,Rspec,我想测试控制器中的方法是否被调用 我的控制器如下所示: def index if id_filters @products = Product.where(id: id_filters) else @products = Product.paginate(params[:page].to_i, params[:per].to_i) end render json: @products, meta: @products.meta end 我看到有人使用下面的代码来执

我想测试控制器中的方法是否被调用

我的控制器如下所示:

def index
  if id_filters
    @products = Product.where(id: id_filters)
  else
    @products = Product.paginate(params[:page].to_i, params[:per].to_i)
  end

render json: @products, meta: @products.meta
end
我看到有人使用下面的代码来执行此操作,因此我尝试在RSpec中使用以下代码进行测试:

controller.stub!(:paginate).and_return true
但是,我得到一个错误:

undefined method `stub!' for #<ProductsController:0x00000102bd4d38>

尽管结果相同,但它是一个未定义的方法。

正确的语法

如果您使用的是3.0版之前的rspec,则正确的语法为

controller.should receive(:paginate).and_return(true)
# OR this equivalence
controller.should receive(:paginate) { true }
# OR (when you are in "controller" specs)
should receive(:paginate) { true }
expect(controller).to receive(:paginate) { true }
# OR (when you are in "controller" specs)
is_expected.to receive(:paginate) { true }
如果您使用的是rspec版本3.0或更高版本,则正确的语法为

controller.should receive(:paginate).and_return(true)
# OR this equivalence
controller.should receive(:paginate) { true }
# OR (when you are in "controller" specs)
should receive(:paginate) { true }
expect(controller).to receive(:paginate) { true }
# OR (when you are in "controller" specs)
is_expected.to receive(:paginate) { true }
您的代码

您似乎正在测试
paginate
中的
Product
,因此您的语法应该是:

# Rspec < 3.0
Product.should receive(:paginate) { true }
# Rspec >= 3.0
expect(Product).to receive(:paginate) { true }
#Rspec<3.0
Product.should接收(:paginate){true}
#Rspec>=3.0
期望(产品).接收(:paginate){true}

我想你的意思是作为一个存根产品,而不是控制器。

非常感谢!使用Rails3.0,所以expect(Product).to receive(:paginate){true}工作得很好。现在,这产生了一个新的问题(以防您还没有意识到我对RSpec非常陌生)。