2012-09-20 60 views
0

我正在關注Net.Tutsplus.com上的Rspec測試教程。 我發現我無法解決的問題。這裏的東西。Net.tutorialplus.com -Rspec教程 - NoMethodError

當我運行測試:

C:\ PROJEKT> rspec的投機/ 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」問題,但它仍然apper。 問題在哪裏?

感謝您的幫助!

回答

1

undefined method books for nil:NilClass (NoMethodError)只是表示您正在調用一個方法books上的東西是零,在這種情況下,@lib

您需要將定義爲@libbefore(:each)掛鉤置於上下文中或描述塊中,在您的代碼中,它在describe '#new'塊中不可用。

另外,在定義it "has five books"規範後,您錯過了一個做法。

我已經糾正了以下這些錯誤:

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 
+0

非常感謝您! – szatan

相關問題