Ruby - Making test pass

我的未来我决定 提交于 2019-12-11 12:25:46

问题


I'm trying to make this test pass and am not sure how to go about making this pass.

TEST

def test_it_is_thirsty_by_default
  vampire = Vampire.new("Count von Count")
  assert vampire.thirsty?
end

def test_it_is_not_thirsty_after_drinking
  vampire = Vampire.new("Elizabeth Bathory")
  vampire.drink
  refute vampire.thirsty?
end

CODE

def thirsty?
  true
end

def drink
  thirsty? === false
end

It is giving a failure message on the last test:

Failed refutation, no message given

What am I missing? My thought is that initially, the vampire is thirsty(true) and then defined a method that would then make the vampire not thirsty(false).

EDIT

Even if I reassign the drink method to:

thirsty? = false

I get a syntax error pointing to the = sign.


回答1:


You're missing a couple things, most importantly some kind of writer method that allows you to store that fact that @thirsty is getting updated inside of your drink method call

There's a couple different ways to do this but I've shown one below with a few notes:

require 'test/unit'

class Vampire
  def initialize(name)
    @name = name
    @thirsty = true # true by default
  end

  def drink
    @thirsty = false # updates @thirsty for the respective instance
  end

  def thirsty?
    @thirsty
  end
end

class VampireTests < Test::Unit::TestCase
  def test_it_is_thirsty_by_default
    vampire = Vampire.new("Count von Count")
    assert vampire.thirsty?
  end

  def test_it_is_not_thirsty_after_drinking
    vampire = Vampire.new("Elizabeth Bathory")
    vampire.drink
    refute vampire.thirsty?
  end
end


来源:https://stackoverflow.com/questions/56420576/ruby-making-test-pass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!