我正在使用 RSpec 进行测试,而且我是 TDD 新手,我已经广泛搜索了解决方案,但我找不到任何真正适合我遇到的问题的东西。我正在使用 FactoryGirl 创建我的对象。我已经编写了传递 belongs_to has_many 关联的测试。但是最后一个测试失败了,即使上面的测试通过了费用的存在,费用数组也总是空的。
describe "expenses associations" do
before { @job.save }
let(:expense_one) { FactoryGirl.create(:expense, job: @job) }
let(:expense_two) { FactoryGirl.create(:expense, job: @job) }
it "should have expenses" do
# This test passes
expect(@job.expenses.find_by(id: expense_one.id).expenseamount).to eq expense_one.expenseamount
expect(expense_one.expenseamount).to eq 12.34
end
it "should destroy associated expenses" do
expenses = @job.expenses(true).to_a
#This expectation passes
expect(expense_one.job_id).to eq @job.id
#This expectation will fail
expect(expenses).not_to be_empty
end
这是模型
class Job < ActiveRecord::Base
has_many :expenses, dependent: :destroy
validates :jobname, presence: true
validates :jobamount, format: { with: /\A\d{1,6}(\.\d{0,2})?\z/ },
numericality: [greater_than_or_equal_to: 0, less_than_or_equal_to: 999999]
validates :paidamount, format: { with: /\A\d{1,6}(\.\d{0,2})?\z/ },
numericality: [greater_than_or_equal_to: 0]
validate :not_in_the_future
validate :paid_less_than_billed
class Expense < ActiveRecord::Base
validates :expenseamount, format: { with: /\A\d{1,5}(\.\d{0,2})?\z/ },
numericality: [greater_than_or_equal_to: 0, less_than_or_equal_to: 99999]
validates :expensename, presence: true
validates :job_id, presence: true
belongs_to :job