Ruby - 如何替换之前:每个都有一个let?

时间:2014-04-13 15:35:10

标签: ruby testing rspec let

我有:

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,即

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

1 个答案:

答案 0 :(得分:1)

let方法将定义方法,而不是实例变量。换句话说,过去@random_song现在只需要random_song

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