微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rspec:如何创建模拟关联

我有以下课程:

class Company < ActiveRecord::Base

  validates :name,:presence => true

  has_many :employees,:dependent => :destroy

end


class Employee < ActiveRecord::Base

  validates :first_name,:presence => true
  validates :last_name,:presence => true
  validates :company,:presence => true   

  belongs_to :company

end

我正在为Employee类编写测试,所以我正在尝试为Employee使用的公司创建double.

下面是我的Rspec的片段

let(:company) { double(Company) }
let(:employee) { Employee.new(:first_name => 'Tom',:last_name => 'Smith',:company => company) }

context 'valid Employee' do

it 'will pass validation' do
  expect(employee).to be_valid
end

it 'will have no error message' do
  expect(employee.errors.count).to eq(0)
end

it 'will save employee to database' do
  expect{employee.save}.to change{Employee.count}.from(0).to(1)
end

end

我收到了所有3次测试的错误消息

ActiveRecord::AssociationTypeMismatch:
   Company(#70364315335080) expected,got RSpec::Mocks::Double(#70364252187580)

我认为我试图创造双重的方式是错误的.您能否指导我如何创建一个可以被Employee用作其关联的公司的双重身份.

我没有使用FactoryGirl.

非常感谢.

解决方法

没有一个很好的方法可以做到这一点,我不确定你还需要.

您的前两个测试基本上是测试相同的东西(因为如果员工有效,employee.errors.count将为0,反之亦然),而您的第三个测试是测试框架/ ActiveRecord,而不是您的任何代码.

正如其他答案所提到的那样,Rails在以这种方式进行验证时需要相同的类,所以在某些时候你必须坚持公司.但是,您可以在一次测试中完成此操作,并在所有其他测试中获得所需的速度.像这样的东西:

let(:company) { Company.new }
let(:employee) { Employee.new(:first_name => 'Tom',:company => company) }

context 'valid Employee' do
  it 'has valid first name' do
    employee.valid?
    expect(employee.errors.keys).not_to include :first_name
  end

  it 'has valid last name' do
    employee.valid?
    expect(employee.errors.keys).not_to include :last_name
  end

  it 'has valid company' do
    company.save!
    employee.valid?
    expect(employee.errors.keys).not_to include :company
  end
end

如果你真的想继续你的第三次测试,你可以包括company.save!在你的阻止,或禁用验证(虽然,你甚至在那时测试什么?):

it 'will save employee to database' do
  expect{employee.save!(validate: false)}.to change{Employee.count}.from(0).to(1)
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐