Rspec 模拟:ActiveRecord::AssociationTypeMismatch [英] Rspec Mocking: ActiveRecord::AssociationTypeMismatch

查看:20
本文介绍了Rspec 模拟:ActiveRecord::AssociationTypeMismatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rspec 的新手,正在尝试为用户配置文件设置测试.个人资料属于用户.

I'm new to Rspec and trying to set up a test for a User Profile. Profile belongs_to User.

现在,我通过用户模型与第三方站点进行了 API 集成,但该 API 链接的某些信息包含在 Profile 中,因此我在 Profile 上有一个after_update"过滤器,可以告诉父级用户保存,触发 API 更新.

Now, I have an API integration with a third party site that works through the User Model, but some of the information for that API link is contained in Profile, so I have an "after_update" filter on Profile that tells the parent user to save, which triggers an update of the API.

我正在尝试为此编写一个测试,并且收到 ActiveRecord::AssociationTypeMismatch.原因是我使用的是模拟用户,但我试图测试在更新配置文件时它会发送 :save 给用户.另外,User 模型有一个电子邮件确认过程和上述 API 调用在它的创建过程中,因此实际创建用户只是为了测试这一点确实不理想.

I'm trying to write a test for this, and I'm getting an ActiveRecord::AssociationTypeMismatch. The reason is I'm using a mock user, but I'm trying to test that when Profile is updated it sends :save to User. Plus, the User model has an email confirmation process and the afformentioned API calls in it's create process, so it really isn't ideal to actually create a user just to test this out.

这是我的测试:

it "should save the parent user object after it is saved" do
    user = double('user', :save => true )
    profile = Profile.create( :first_name => 'John', :last_name => 'Doe' )
    profile.user = user

    user.should_receive(:save)
end

因此,很明显,ActiveRecord 错误是由于尝试将模拟用户与期望关联真实用户的配置文件相关联造成的.

So, clearly the ActiveRecord error is being caused by trying to associate a mock user with a profile that expects a real user to be associated.

我的问题是,你在编写 Rails 测试时如何避免这种问题?我想让这个测试做的就是确保 Profile 调用 :save 在它的父用户上.有没有更聪明的方法来做到这一点,或者 ActiveRecord 错误的解决方法?

My question is, how do you avoid this kind of problem in writing rails tests? All I want this test to do is make sure Profile calls :save on it's parent User. Is there a smarter way to do this, or a workaround for the ActiveRecord error?

谢谢!

推荐答案

我发现解决这个问题的唯一方法是使用 Factory 用户而不是模拟.这很令人沮丧,但是在测试两个 ActiveRecord 模型之间的回调时,您必须使用真实模型,否则保存调用将失败,生命周期不会发生,并且无法测试回调.

I found the only way I was able to get around this problem was to use a Factory user instead of a mock. That's frustrating, but when testing the callbacks between two ActiveRecord models you have to use the real models or else save calls will fail, the lifecycle won't happen, and the callbacks can't be tested.

这篇关于Rspec 模拟:ActiveRecord::AssociationTypeMismatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆