使用参数传递时,rspec存根返回nil

时间:2016-07-19 16:41:00

标签: ruby-on-rails rspec-rails stub

我陷入了控制器测试,测试方法是在模块中定义的。

以下是模块

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

以下是具有操作的控制器,其中称为方法

  @portfolio_suggestion_object = fetch_suggested_portfolio(arg1, arg2)

现在,当我使用 binding.pry 检查存根行时,它返回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'

我的代码有什么问题,任何帮助都会得到真正的赞赏。

1 个答案:

答案 0 :(得分:0)

您已定义fetch_suggested_portfolio方法以期望2个参数。您的存根只表示存在该名称的存根,需要2个参数并始终返回字符串“suggested_portfolios”。它实际上并没有为你的电话提供这些论据。

变化:

wealthy.fetch_suggested_portfolio.should be("suggested_portfolios")

是:

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

另外,请考虑使用allow& amp;的新语法。预计。当然,你不必这么做,但你可能会考虑它,因为当你设定期望并创建模拟和实际操作时,你所做的事情会更好。存根。