szatan
szatan

Reputation: 517

Net.tutorialplus.com -Rspec tutorial- NoMethodError

I am following Rspec testing tutorial on Net.Tutsplus.com. I've found problem I couldn't solve. Here the thing.

When I run test:

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

I get:

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 looks like that:

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

Due to tutorial instructions I changed library.rb to:

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

According to tutorial it should solve "books-NoMethodError" problem but it still apper. Where is the problem?

Thanks for help!

Upvotes: 0

Views: 97

Answers (1)

Bitterzoet
Bitterzoet

Reputation: 2792

undefined method books for nil:NilClass (NoMethodError) just means that you are calling a method books on something that is nil, in this case @lib.

You need to place the before(:each) hook that defines @lib inside a context or describe block, in your code it is not available in the describe '#new' block.

Also, you were missing a do after defining the it "has five books" spec.

I've corrected these errors below:

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

Upvotes: 1

Related Questions