在规范中,如何将对象分配给attr_accessor定义的属性?

时间:2014-06-16 11:23:43

标签: ruby-on-rails ruby ruby-on-rails-3 rspec factory-bot

invoice.rb:

class Invoice < ActiveRecord::Base
  attr_accessible :user_obj
  attr_accessor :user_obj

  after_create :create_activity
  def create_activity
    log =  "<b> Invoice created. </b>" + '<br/>' + '<span class="meta"> ' + self.user_obj.name  + ' on ' + Time.now.to_date.strftime('%d-%m') + "</span>"
    @activity = ActivityLog.new(:invoice_id => self.id,:user_id => self.user_obj.id, :log => log)
    @activity.save
  end 

end

invoice_spec.rb:

it "some case for create invoice" do
  @obj = create(:invoice)      # invoice data defined in factory file.
end 

运行spec:

后出错
undefined method `name' for nil:NilClass
# ./app/models/invoice.rb:869:in `create_activity'
# ./spec/models/invoice_spec.rb:246:in `block (3 levels) in <top (required)>'

上面是我的模型invoice.rb,其中包含一个attribute_accessor&#34; user_obj&#34;并包含有关用户的信息,我在&#34; create_activity&#34;方法为&#34; self.user_obj.name&#34;或者&#34; self.user_obj.id&#34;。

我的问题是,当我运行我的规范来创建发票时,它会为&#34; user_obj&#34;没有定义的。那么有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:0)

factory_girl可以将对象分配给attr_accessor定义的属性,就像对模式定义的属性一样容易。

只需撰写:user_obj工厂,并在您的规范中,使用工厂创建UserObj并将其添加到Invoice

it "some case for create invoice" do
  @obj = create :invoice, user_obj: create(:user_obj)
end

如果您希望每个Invoice都拥有UserObj,请为Invoice工厂提供关联:

FactoryGirl.define do
  factory :invoice do
    user_obj
    # invoice attributes ...
  end
end

(这是最简单的语法,当ActiveRecord关联和factory_girl工厂具有相同名称时有效。有关可用语法的更多内容:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

然后你可以说create :invoiceInvoice会有UserObj

附注:只需拨打user_obj user,或其他一些名称,说明为什么它不仅仅是一个用户。 Ruby中的所有东西都是一个对象......