2017-10-17 52 views
1

我想將一些ERB編譯成符合我的規範的燈具內的CSV文件。下面是CSV:如何使用rspec/Rails 5在CSV設備中編譯ERB?

(規格/夾具/文件/ song_info.csv.erb)

song id,  song_title 
<%= song.id %>, Fun Title 

在我的測試,我首先創建一首歌,所以我可以插它的id到夾具,然後負載CSV。

describe "#update" do 
    let(:song) { FactoryGirl.create :song }   # create the instance 
    let(:csv) { file_fixture("song_info.csv.erb").read } # load the file 

    it "finds a song and adds it's title" do   
    # when I look at csv here, it is just a string with the raw ERB 
    end 
end 

在測試中發生的事情並不重要。問題是,當我檢查csv的內容時,我發現它只是一個帶有原始ERB(未編譯)的字符串。

"song_id, new_song_title, <%= song.id %>, Song Title"

如何強制僱員再培訓局編譯? #read不是正確的file_fixture方法?它是完全不同的東西嗎?

注意:我知道還有其他方法可以在沒有燈具的情況下完成此操作,但這只是一個簡單的例子。我只想知道如何將ERB編譯成夾具。

回答

1

您需要創建一個ERB實例,並評價它:

let(:csv) { ERB.new(file_fixture("song_info.csv.erb").read).result(binding) } # load the file 

binding是有點神奇,它會給你Binding類,封裝在代碼中的這個特殊的地方執行上下文的一個實例。更多信息:https://ruby-doc.org/core-2.3.0/Binding.html

如果您需要自定義綁定做更復雜的操作,您可以創建一個類,並生成從那裏的綁定,例如:

require 'csv' 
require 'erb' 

class CustomBinding 
    def initialize(first_name, last_name) 
    @id = rand(1000) 
    @first_name = first_name 
    @last_name = last_name 
    end 

    def get_binding 
    binding() 
    end 
end 

template = <<-EOS 
"id","first","last" 
<%= CSV.generate_line([@id, @first_name, @last_name]) %> 
EOS 

puts ERB.new(template).result(CustomBinding.new("Yuki", "Matz").get_binding) 
相關問題