【问题标题】:Net.tutorialplus.com -Rspec tutorial- NoMethodErrorNet.tutorialplus.com -Rspec 教程- NoMethodError
【发布时间】:2012-09-20 09:08:02
【问题描述】:

我正在关注 Net.Tutsplus.com 上的 Rspec 测试教程。 我发现了我无法解决的问题。事情就是这样。

当我运行测试时:

C:\projekt>rspec spec/library_spec.rb --format 嵌套

我明白了:

C:/projekt/spec/library_spec.rb:35:in `block (3 levels) in <top (required)>': un
defined method `books' for nil:NilClass (NoMethodError)

library_spec.rb 看起来像这样:

require "spec_helper"

    describe "Library Object" do

    before :all do
        lib_arr = [ 
        Book.new("JavaScript: The Good Parts", "Douglas Crockford", :development),
        Book.new("Designing with Web Standarts", "Jeffrey Zeldman", :design),
        Book.new("Don't Make me Think", "Steve Krug", :usability),
        Book.new("JavaScript Patterns", "Stoyan Sefanov", :development),
        Book.new("Responsive Web Design", "Ethan Marcotte", :design)
    ]

    File.open "books.yml", "w" do |f|
        f.write YAML::dump lib_arr
    end

end

before :each do
    @lib = Library.new "books.yml"

end

describe "#new" do
    context "with no parameters" do
        it "has no books" do
            lib = Library.new
            lib.books.length.should == 0
        end
end

    context "with a yaml file name parameters " do
        it "has five books"
        @lib.books.length.should == 5
    end
end
 end

由于教程说明,我将 library.rb 更改为:

require 'yaml'

 class Library
attr_accessor :books

def initalize lib_file = false
    @lib_file = lib_file
    @books = @lib_file ? YAML::load(File.read(@lib_file)) : []
    end
 end

根据教程,它应该解决“books-NoMethodError”问题,但它仍然存在。 问题出在哪里?

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby rspec tdd


    【解决方案1】:

    undefined method books for nil:NilClass (NoMethodError) 只是表示您正在调用一个方法 books 对一个为零的东西,在这种情况下是 @lib

    您需要将定义@libbefore(:each) 钩子放在上下文或描述块中,在您的代码中它在describe '#new' 块中不可用。

    另外,在定义 it "has five books" 规范后,您错过了一个 do。

    我已在下面更正了这些错误:

    describe "#new" do
      before :each do
        @lib = Library.new "books.yml"
      end
    
      context "with no parameters" do
        it "has no books" do
          lib = Library.new
          lib.books.length.should == 0
        end
      end
    
      context "with a yaml file name parameters " do
        it "has five books" do
          @lib.books.length.should == 5
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多