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

查看:70
本文介绍了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.原因是我使用的是模拟用户,但我正在尝试测试更新Profile时是否将: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在其父User上.有没有更聪明的方法可以做到这一点,或者解决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天全站免登陆