【问题标题】:Unable to test a method inside a module in Rspec unit testing for Rails无法在 Rails 的 Rspec 单元测试中测试模块内的方法
【发布时间】:2014-03-31 06:45:21
【问题描述】:

这是我的模块。我喜欢测试方法 load_csv

我参考了这个例子Example Link

并编写了这段代码。下面是模块代码

require 'csv'

module DummyModule
  class Test
    def load_csv(filename)
      CSV.read(filename, :row_sep => "\r", :col_sep => "\t")
    end
  end
end

这是我的 Rspec

require 'spec_helper'

describe DummyModule do
  let(:data) { "title\tsurname\tfirstname\rtitle2\tsurname2\tfirstname2\r" }
  let(:result) { [["title", "surname", "firstname"], ["title2", "surname2", "firstname2"]] }
  before(:each) do
    @attribute_validator = TestAttributeValidator.new

  end

  it "should parse file contents and return a result" do
    puts data.inspect
    puts result.inspect
    File.any_instance.stubs(:open).with("filename","rb") { StringIO.new(data) }
    @attribute_validator.load_csv("filename").should eq(result)
  end
end

class TestAttributeValidator
  include DummyModule
end

它给了我这个错误

DummyModule should parse file contents and return a result
 Failure/Error: @attribute_validator.load_csv("filename").should eq(result)
 NoMethodError:
   undefined method `load_csv' for #<TestAttributeValidator:0xd0befd>
 # ./spec/extras/dummy_module_spec.rb:15:in `(root)'

请帮忙

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 unit-testing rspec


    【解决方案1】:

    你可能不想要你的

    class Test
    

    在您的 module 定义中。像这样,以下将起作用:

    @attribute_validator_tester = TestAttributeValidator::Test.new
    @attribute_validator_tester.respond_to? 'load_csv'
    => true
    

    但这可能不是您想要的。在类中包含module 会将module 的所有“功能”(即所有方法,还有常量和类)添加到包含module 的类中。在您添加的示例中class Test 到 class TestAttributeValidator 的命名空间和此类的 instances 将具有您想要的方法 load_csv。

    只需省略 module 中的类定义,一切都会好起来的。

    【讨论】:

    • 您上面的代码解决了我的问题。但是现在我得到了这个错误..你对此有任何想法吗?失败/错误:@attribute_validator_tester.load_csv("filename").should eq(esult) Errno::ENOENT: No such file or directory - filename # ./app/extras/dummy_module.rb:6:in load_csv' # ./spec/extras/dummy_module_spec.rb:15:in (root )'
    • 如果您使用了上面的“代码”(我宁愿称其为笨拙的解决方法),您可能还没有理解答案。如果您刚刚从您的DummyModule 中删除了class Test ... end,那么您的代码将会起作用。
    • 是的,我删除了,很好。但是当尝试测试打开 csv 文件并获取数据时出现错误
    【解决方案2】:

    (添加另一个答案,因为这确实是另一个问题)

    谷歌搜索Errno::ENOENT 会导致this answer,但这几乎没有必要,因为错误消息确实告诉您,找不到您的文件。由于您为"filename" 存根,因此应该找到 if 您正在使用的CSV 版本仍然使用open 打开文件(当前的ruby CSV 读者似乎这样做, see the source) 那么它实际上应该可以工作。

    但是,根据您的 ruby​​ 版本,CSV 库可能会添加更多选项,我引用的版本将 universal_newline: false 合并到 open 的选项中,因此您的存根不会具有它期望和转发的所有参数您对“常规”方法的调用找不到您的"filename"。您应该相应地检查您的 ruby​​ 和存根的确切版本。

    这可能是像 ruby​​ 这样的动态语言所带来的遗产的一部分 :-)

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 2016-10-17
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多