
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 valIDates :company,:presence => true belongs_to :companyend
我正在为Employee类编写测试,所以我正在尝试为Employee使用的公司创建double.
下面是我的Rspec的片段
let(:company) { double(Company) }let(:employee) { Employee.new(:first_name => 'Tom',:last_name => 'Smith',:company => company) }context 'valID Employee' doit 'will pass valIDation' do expect(employee).to be_valIDendit 'will have no error message' do expect(employee.errors.count).to eq(0)endit 'will save employee to database' do expect{employee.save}.to change{Employee.count}.from(0).to(1)endend 我收到了所有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 endend 如果你真的想继续你的第三次测试,你可以包括company.save!在你的阻止,或禁用验证(虽然,你甚至在那时测试什么?):
it 'will save employee to database' do expect{employee.save!(valIDate: false)}.to change{Employee.count}.from(0).to(1)end 总结 以上是内存溢出为你收集整理的ruby-on-rails – Rspec:如何创建模拟关联全部内容,希望文章能够帮你解决ruby-on-rails – Rspec:如何创建模拟关联所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)