【问题标题】:RSpec stub with unexpected results具有意外结果的 RSpec 存根
【发布时间】:2015-07-23 02:14:32
【问题描述】:

我正在用 Ruby 编写 Rock Paper Scissors Lizard Spock 的游戏命令行。我有matchup 方法,它采用变量@shape(游戏随机选择的手形)和@player_shape(玩家选择的手形)。

我的matchup 方法比较两个形状并将游戏结果设置为@result

class Game
  SHAPES = [:rock, :paper, :scissors, :lizard, :spock]
  attr_reader :shape, :player_shape, :status

  # ...

  def matchup
    if @shape == @player_shape
      @result = :draw
    else
      case @player_shape
      when :rock
        @result = (@shape == :scissors || @shape == :lizard) ? :player_wins : :game_wins
      when :paper
        @result = (@shape == :rock || @shape == :spock) ? :player_wins : :game_wins
      when :scissors
        @result = (@shape == :paper || @shape == :lizard) ? :player_wins : :game_wins
      when :lizard
        @result = (@shape == :paper || @shape == :spock) ? :player_wins : :game_wins
      when :spock
        @result = (@shape == :rock || @shape == :scissors) ? :player_wins : :game_wins
      end
    end
  end

  # ...
end

我多次运行代码,它按预期工作,但在我的规范文件中,我得到的结果与代码行为不匹配。这是规格:

describe Game do
  subject(:game) { Game.new }
  # ...
  describe "#matchup" do
    context "game chooses rock" do
      before do
        allow(game).to receive(:shape).and_return(:rock)
      end

      it "sets result as :player_wins if the game chooses paper" do
        allow(game).to receive(:player_shape).and_return(:paper)

        game.matchup

        expect(game.result).to eq(:player_wins)
     end
    end
  end
end

结果如下:

Failure/Error: expect(game.result).to eq(:player_wins)

   expected: :player_wins
        got: :draw

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -:player_wins
   +:draw

我在这里做错了什么?我试了又试,还是不知道怎么解决这个问题。

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    这里

    allow(game).to receive(:shape).and_return(:rock)
    

    还有

    allow(game).to receive(:player_shape).and_return(:paper)
    

    您正在为 game 对象存根方法 Game#shapeGame#player_shape。 但是您在if 语句中使用@shape == @player_shape 作为条件。

    Ruby 默认将未定义的实例变量(以@ 开头的变量)视为nil

    → irb
    irb(main):001:0> @shape
    => nil
    

    因此,@shape == @player_shape 与您的情况下的 nil == nil 相同。这实际上是一个true。程序流到@result = :draw行的原因是什么。

    要使其工作,您需要使用 attr_reader 定义 shapeplayer_shape 方法,例如,使用它们而不是实例变量。

    更新

    现在在您的代码中将@shape 替换为shape@player_shapeplayer_shape。确保为它们初始化值。

    查看有关实例变量的 that Ruby Monk tutorial(或任何其他文章)以了解它们的工作原理

    【讨论】:

    • 我添加了 shapeplayer_shape 方法,它仍然给我相同的结果。 (我已经更新了问题以表明这一点)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2015-04-30
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多