【问题标题】:RSpec can't define singleton error when trying to mock gets and puts for Hash Elements尝试模拟哈希元素的获取和放置时,RSpec 无法定义单例错误
【发布时间】:2013-07-20 09:35:11
【问题描述】:

我有一个图书模型,它是一个 ruby​​ 脚本,它为程序中提到的某些预定义图书标题分配价格。这是书本模型的外观:-

class Book

  attr_accessor :books  
  def initialize books
    puts "Welcome to setting book price program"
    @books = books
  end

  def get_prices
    puts "Please enter appropriate price for each book item:-"
    count = 0
    @books = @books.inject({}) { |hash, book|
      print "#{book.first}: "
      price = STDIN.gets.chomp
      while (price !~ /^[1-9]\d*$/ && price != "second hand")
        puts "Price can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate price in integer"
        price = STDIN.gets.chomp #gets.chomp - throws error
      end
      price == "second hand" ? price = "100" : price #takes a default price
      hash[book.first] = price.to_i
      hash
    }
  end

end

books = {"The Last Samurai" => nil,
         "Ruby Cookbook" =>  nil,
         "Rails Recipes" =>  nil,
         "Agile Development with Rails" =>  nil,
         "Harry Potter and the Deathly Hallows" =>  nil}


book_details = Book.new(books)
book_details.get_prices
puts "\n*******Books Details:#{book_details.books}******\n"

我正在尝试编写一个测试用例来检查每本书的价格输入是否正确。如果价格输入不正确,它应该要求用户重新输入正确的价格。该程序做得很好。但是当我尝试使用 RSpec 模拟这种行为时,我遇到了困难。

require 'spec_helper'

describe Book do

  before :each do
    books = {"The Last Samurai" => nil,
         "Ruby Cookbook" =>  nil,
         "Rails Recipes" =>  nil,
         "Agile Development with Rails" =>  nil,
         "Harry Potter and the Deathly Hallows" =>  nil}
    @book = Book.new(books)
  end

  describe "#new" do
    it "Should be an instance of the Book" do
      @book.should be_an_instance_of Book
    end
  end

  describe "#getprice" do
    it "Should get the price in the correct format or else return appropriate error" do
      puts "\n************************************************************************\n"
      book_obj = @book
      STDOUT.should_receive(:puts).and_return("Welcome to setting book price program")
      book_obj.get_prices.should_not be_nil
      book_obj.books["The Last Samurai"].stub!(:gets) {"40"} #trying to set the value for one book using Hash
      book_obj.books["The Last Samurai"].should == 40 #verifying the value set for a particular key is accurate
    end
  end

end

你甚至可以在 Github 上 clone this code 来试试这个。我正在使用 Ruby 1.9.3 和 rspec 2.11.0

The error that I'm getting currently is:-

Failures:

  1) Book#getprice Should get the price in the correct format or else return appropriate error
     Failure/Error: book_obj.books["The Last Samurai"].stub!(:gets) {"40"} #trying to set the value for one book using Hash
     TypeError:
       can't define singleton
     # ./spec/book_spec.rb:31:in `block (3 levels) in <top (required)>'

Finished in 7.61 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/book_spec.rb:21 # Book#getprice Should get the price in the correct format or else return appropriate error

更新问题

对于错误的用户输入,使用下面的测试用例,我收到以下错误。我怎样才能正确处理这个?我尝试了几个选项,但它们似乎都失败了。请参阅作为规范 sn-p 一部分的每个选项的注释。

 it "Incorrect input format should return error message asking user to re input" do
      puts "\n************************************************************************\n"
      book_obj = @book
      STDIN.stub(:gets) { "40abc" }

      #book_obj.get_prices.should be_nil --> adding this line of code goes into an infinite loop with the error message below
      #Price cannot be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate duration in integer\n

      STDOUT.should_receive(:puts).and_return("Price cannot be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate duration in integer\n")

      #the below two tests fails with syntax error - don't seem that easy to figure out what's going wrong

      #STDOUT.should_receive("Price cannot be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate duration in integer\n")
      #STDOUT.should == "Price cannot be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate duration in integer\n"
    end


Failures:

  1) Book#getprice Incorrect input format should return error message asking user to re input
     Failure/Error: STDOUT.should_receive(:puts).and_return("Price cannot be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate duration in integer\n")
       (#<IO:0x00000001c7b298>).puts(any args)
           expected: 1 time
           received: 0 times
     # ./spec/book_spec.rb:40:in `block (3 levels) in <top (required)>'

我非常感谢任何关于如何做到这一点的指导。谢谢。

【问题讨论】:

    标签: hash io mocking rspec2 ruby-1.9.3


    【解决方案1】:

    如果您使用--backtrace 标志运行规范,您会看到在https://github.com/rspec/rspec-mocks/blob/v2.13.0/lib/rspec/mocks/method_double.rb#L140 上引发了错误,其中rspec-mocks 正在尝试获取被存根或模拟的对象的单例类。这适用于大多数类的实例,但规范中有错误。

    代码将gets 发送到STDIN,但规范试图在book_obj.books["The Last Samurai"] 上存根gets,这在当时是一个int,你不能从@ 得到一个单例987654330@:

    $ irb
    1.9.3-p392 :001 > class << 1; self; end
    TypeError: can't define singleton
            from (irb):1
        from /Users/david/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
    

    如果我理解正确,您想进行两项更改。首先,将脚本的最后几行移动到一个单独的文件中,当您运行规范时不会加载该文件,例如bin/books(它可能需要 book.rb 然后添加这些行)。

    接下来,删除在book_obj.books["The Last Samurai"] 上存根gets 的行,并在STDIN 上添加一个存根gets 的行,在调用get_prices 的行之前(即当与STDIN 发生交互时):

    STDIN.stub(:gets) { "40" }
    book_obj.get_prices.should_not be_nil
    

    这至少会让你的规范通过。

    一般来说,直接处理 STDIN 和 STDOUT 的代码很难在对象级别规范,因为像 rspec、minitest 等测试工具都使用 STDOUT 来呈现它们的信息,所以你结束了在外壳中有很多令人困惑的噪音。我建议要么更改设计以将输入/输出流注入到 book 类(运行脚本时可以是 STDIN 和 STDOUT,但运行 rspec 时测试双打),或者使用像 @ 这样的工具987654322@,旨在指定交互式 shell 脚本。

    【讨论】:

    • 首先,非常感谢您尝试帮助我解决此问题。您的建议确实有助于处理以正确格式给出的用户输入。尽管尝试了几种组合,但我仍然无法解决糟糕的用户输入问题(请参阅更新的问题以及代码和错误的详细信息)。我还有一件事要问,如果我遗漏了什么,请原谅我的无知.. 在尝试存根存根时 book_obj.books["The Last Samurai"] 我只是想为键分配一个值,所以我真的不明白那里是什么..请解释一下..谢谢
    • 无限循环是因为get_prices 中的while 循环。您需要将错误输入和良好输入都存根以通过例如STDIN.stub(:gets) { "40abc" }; STDIN.stub(:gets) { "40" };.
    • 语法错误是因为你说STDOUT 应该接收一个字符串,但它应该接收puts with 一个字符串,例如STDOUT.should_receive(:puts).with("this string")。您正在尝试查找名为“价格不能为 0 或负整数或十进制格式或字母数字的方法。\n请以整数输入适当的持续时间\n”,因此出现语法错误。
    • David,根据您对错误输入规范的建议,我已更新文件。请查看更改here。我仍然遇到无限循环,我猜规范没有出现(这是通过链接共享的实际代码中的第 33 行),我可以在其中检查以下条件 - STDOUT.should_receive(:puts) .with("this string") 可能是我需要先正确处理无限循环,但不知何故我还不能到达那里。谢谢。
    • 我想在这里发表评论,因为我犯了一个非常愚蠢的错误,我浪费了时间试图弄清楚。我收到与 OP 相同的错误消息。它没有回答 OP 的问题,但它可能会帮助其他人。我(愚蠢地)试图在符号而不是原始对象上创建一个存根:allow(:object).to receive(:method) 当它应该是:allow(object).to receive(:method)
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2020-08-31
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多