简体   繁体   English

如何在带有Rails的模型测试的模型中访问哈希声明的元素?

[英]How can I access the elements of a hash declare in a model with a model test in rails?

I have declared a model used solely to print a csv file. 我声明了仅用于打印csv文件的模型。 This model stores its values in a hash as such: 该模型将其值存储在哈希中,如下所示:

class MyObject < ParentObject

  def initialize(args = {})
    super(args)
    @campaign = args[:symbol]
    @campaign.report.data[:donations][:tiers].each do |tier|
      @data = []
      tmp_arr = []
      @data << ['Date','User Name','Email']

      tier.values.sort{|a,b| a.name <=> b.name}.each do |c|
        tmp_arr = []
        tmp_arr << c.created_at
        tmp_arr << c.user.name
        tmp_arr << c.user.email
        @data << tmp_arr
      end
    end
  end
end

In ParentObject, I access the value of @data and use it to generate a csv file. 在ParentObject中,我访问@data的值并使用它生成一个csv文件。 I need to test this initialization method in an rspec test, but when I try to access @data, I receive a value of nil. 我需要在rspec测试中测试此初始化方法,但是当我尝试访问@data时,会收到nil值。

How can I test this initialization method? 如何测试此初始化方法?

The spec is 规格是

describe Object do
    it "should store donor information" do
        @user = FactoryGirl.build(:user)
        @campaign = FactoryGirl.build(:current_campaign)
        @contribution_tier = FactoryGirl.build(:contribution_tier, campaign: @campaign)
        @contribution = FactoryGirl.build(:contribution, campaign: @campaign, user: @user)

        @donor = Reports::Donors.new(campaign: @campaign)

        puts @data.first
    end

Use instance_variable_get() 使用instance_variable_get()

You can refer this link for example 您可以参考此链接的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM