rspec stub returns nil 当传递参数时

rspec stub returns nil when passed with arguments

我被困在控制器测试中,使用模块中定义的测试方法。

这是模块

module CommonConcern
extend ActiveSupport::Concern
...
def fetch_suggested_portfolio(user_portfolio, amount)
PortfolioService::Suggestion
  .call(duration: user_portfolio.duration,
        risk_level: user_portfolio.risk_level,
        amount: amount,
        investment_plan: user_portfolio.investment_plan,
        portfolio_type: user_portfolio.portfolio_type)
end

这里是调用方法的带有action的controller

  @portfolio_suggestion_object = fetch_suggested_portfolio(arg1, arg2)

现在,当我使用 binding.pry 检查我的 stub 行时,它 returns nil

wealthy.stub(:fetch_suggested_portfolio).with(@portfolios, @portfolios.amount).and_return("suggested_portfolios")

还有下一行,即

wealthy.fetch_suggested_portfolio.should be("suggested_portfolios")

报错如下:

Failure/Error: wealthy.fetch_suggested_portfolio.should be("suggested_portfolios")

 ArgumentError:
   Wrong number of arguments. Expected 2, got 0.

我也在使用 'rspec-rails', '3.4.2'

我的代码有什么问题,任何帮助将不胜感激。

您已将 fetch_suggested_portfolio 方法定义为需要 2 个参数。你的存根只说有一个那个名字的存根,它需要 2 个参数并且总是 returns 字符串 "suggested_portfolios"。它实际上并没有为您的调用提供这些参数。

变化:

wealthy.fetch_suggested_portfolio.should be("suggested_portfolios")

成为:

wealthy.fetch_suggested_portfolio(something, something_else).should be("suggested_portfolios")

另外,考虑使用 allows & expects 的新语法。当然,您不必这样做,但您可能会考虑它,因为当您设定期望并创建模拟和存根时,它在您实际做的事情方面读起来更好。