【问题标题】:rspec private method test with factory_girl使用 factory_girl 进行 rspec 私有方法测试
【发布时间】:2013-04-08 05:28:00
【问题描述】:

cashout.rb

class Cashout < ActiveRecord::Base
  belongs_to :partner
private
  def partner_exist?
    if self.partner.nil?
      errors.add(:base, "There is no partner! ")
      return false;
    end
    return true
  end
end

cashout_spec.rb

context 'should check partner existence' do 
    it 'if partner is not nil' do 
      @company = Factory(:company) 
      @partner = Factory(:partner, :company => @company)
      @cashout = Factory.build(:cashout, :partner => @partner)
      @cashout.save
      @cashout.partner_exist?.should eql(true)
    end
end

这些是我的模型文件和测试文件。测试结果是

1) Cashout should check partner existence if partner is nil
     Failure/Error: @cashout3.partner_exist?.should eql(false)
     NoMethodError:
       private method `partner_exist?' called for #<Cashout:0x007f822189dfa0>
     # ./spec/models/cashout_spec.rb:47:in `block (3 levels) in <top (required)>'

你知道如何测试私有方法吗?

【问题讨论】:

  • 我假设partner_exist? 在另一个方法或回调中被调用,所以你为什么不在你调用save 时测试你的模型中是否存在"There is no partner!" 错误对于有和没有partner? 的两种情况

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


【解决方案1】:

你可以通过send调用私有方法:

@cashout3.send(:partner_exist?).should eql(false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2019-03-12
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多