我正在运行ruby 2.0.0& Rails 4.0.2
我的模型看起来像:
class Activity < ActiveRecord::Base
has_many :beneficiaries, -> {includes([:beneficiary_type, :gender])}
def number_of_beneficiaries(gender, type)
number = 0
beneficiaries.each do |b|
number = b.quantity if b.gender.name == gender && b.beneficiary_type.name == type
end
number
end
end
失败模型的规范如下:
require 'spec_helper'
describe Activity do
it "return number of beneficiaries by gender and type" do
beneficiary_1 = Beneficiary.new(:quantity => 15, :gender => Gender.find_by_name('hombres'), :beneficiary_type => BeneficiaryType.find_by_name('adultos'))
beneficiary_2 = Beneficiary.new(:quantity => 10, :gender => Gender.find_by_name('mujeres'), :beneficiary_type => BeneficiaryType.find_by_name('niños'))
activity = Activity.new
activity.beneficiaries << beneficiary_1
activity.beneficiaries << beneficiary_2
expect(activity.number_of_beneficiaries('hombres', 'adultos')).to eq 15
end
end
这给了我。
1)活动按性别和类型返回受益人数量 失败/错误:期望(activity.number_of_beneficiaries('hombres','adultos'))。到eq 15
expected: 15 got: 10 (compared using ==) # ./spec/models/activity_spec.rb:30:in `block (2 levels) in <top (required)>'
奇怪的是,如果我颠倒了我指定受益人的顺序,它就会通过测试。
如果我测试预期的受益人数,则正确回答2。