문제

나는 가지고있다 :

describe "and for a given song" do
  before :each do
    srand(96)
    @random_song=@playlist.random_song
  end

  it "it can get the last letter" do
    expect(@playlist.ending(@random_song)).to eq 'a'
  end     
end
.

@random_song을 let, i.e로 옮길 원합니다.

describe "and for a given song" do
  before :each do
    srand(96)
  end

  let(:random_song) {@playlist.random_song}

  it "it can get the last letter" do
    expect(@playlist.ending(@random_song)).to eq 'a'
  end     
end
.

그러나 나는 얻는다

undefined method `[]' for nil:NilClass
.

@playlist는 이전에 정의되어 있으며, 이전 코드는 다음과 같습니다.

require './playlist.rb'
describe Playlist do
  it "exists" do
    playlist=Playlist.new
    expect(playlist).to be
  end
end
describe "Playlist should be able to open the song file" do
  it "without error" do
    expect(File.open('SongLibrary.xml')).to be
  end

  before :each do
    @playlist=Playlist.new
    @file='SongLibrary.xml'
    @playlist.songs= @file
  end

  it"and store the results in ruby" do
    expect(@playlist.songs.size).to eq 5115
  end

  it "and pick a random song" do
    srand(96)
    random_song=@playlist.random_song
    expect(random_song).to eq 'La Dolce Vita'
  end


  describe "and for a given song" do

    before :each do
      srand(96)
#      @random_song=@playlist.random_song
    end

    let(:random_song) {@playlist.random_song}

    it "it can get the last letter" do
      expect(@playlist.ending(@random_song)).to eq 'a'
    end

  end

end
.

테스트중인 실제 코드는

입니다.
class Playlist

  require 'nokogiri'

  attr :songs

  def initialize
    @songs=[]
  end 

  def songs=(file)
    doc = Nokogiri.XML( IO.read( 'SongLibrary.xml' ) ) 
    @songs=doc.css( 'Song' ).map{|s| s['name'] }
  end 

  def random_song
    @songs[rand(@songs.size)]
  end 

  def ending(song)
    song[-1]
  end 

end
.

도움이 되었습니까?

해결책

let 메소드를 정의합니다.인스턴스 변수가 아닌 방법.즉, @random_song로 사용되는 것은 이제 random_song가 필요합니다.

it "it can get the last letter" do
  expect(@playlist.ending(random_song)).to eq 'a'
end
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top