加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:08:48 所属栏目:百科 来源:网络整理
导读:我有以下课程: class Company ActiveRecord::Base validates :name,:presence = true has_many :employees,:dependent = :destroyendclass Employee ActiveRecord::Base validates :first_name,:presence = true validates :last_name,:presence = true val
我有以下课程:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读