2017-10-17 53 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) 
相关问题