【问题标题】:rspec mock not getting called on belongs_to associationrspec 模拟未在 belongs_to 关联上被调用
【发布时间】:2013-04-25 12:16:20
【问题描述】:

我正在尝试使用 RSpec 在 Rails 中测试我的控制器,但它没有调用我制作的模拟之一,我不知道为什么。

我的模型有一个用户类,一个游戏类,一个玩家类,分别属于一个用户和一个游戏。

我正在尝试测试类似的东西

player = Player.find_by_id(params[:id])
if player != nil && player.user == current_user && player.game.remove_player?(player)
  redirect_to games_url

但我似乎无法模拟 remove_player?正确。我正在做的几乎是这样的:

@player = double("player")
Player.should_receive(:find_by_id).with(mock_player_id.to_s).and_return { @gplayer }
@player.stub(:user).and_return(@current_user)
fakeGame = double("game")
@player.stub(:game).and_return(fakeGame)
fakeGame.should_receive(:remove_player?).with(@player).and_return(true)

我收到错误消息说 remove_player?从未被调用。知道我做错了什么吗?我不能确定它是否到达 player.user ==curent_user,但它正在调用 find_by_id 并且根本没有抱怨它,所以我想它必须到达用户检查。

编辑:@current_user 确实等于 current_user

另外,我尝试将第 3 行替换为

fakeUser = double("user")
@player.should_receive(:user).and_return(@current_user)

它给了我一个错误说:用户没有被调用。

【问题讨论】:

    标签: ruby-on-rails rspec mocking


    【解决方案1】:

    在规范的第二行,返回@player 而不是@gplayer。如果未定义 @gplayer,您的 find_by_id 将在您的规范中返回 nil,因此您的 if 条件将在到达 remove_player 之前短路。

    【讨论】:

    • 男人不敢相信我花了 2 个小时寻找错误的地方,但从未发现过。谢谢。抱歉这个愚蠢的问题。
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多