简体   繁体   English

Rspec Mocking:ActiveRecord :: AssociationTypeMismatch

[英]Rspec Mocking: ActiveRecord::AssociationTypeMismatch

I'm new to Rspec and trying to set up a test for a User Profile. 我是Rspec的新手并尝试为用户配置文件设置测试。 Profile belongs_to User. 个人资料belongs_to用户。

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. 现在,我与通过用户模型工作的第三方站点进行了API集成,但该API链接的一些信息包含在Profile中,因此我在Profile上有一个“after_update”过滤器,告诉父用户保存,触发API的更新。

I'm trying to write a test for this, and I'm getting an ActiveRecord::AssociationTypeMismatch. 我正在尝试为此编写一个测试,我正在获得一个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. 原因是我正在使用模拟用户,但我正在尝试测试当Profile更新时它发送:保存到用户。 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. 此外,用户模型还有一个电子邮件确认过程以及在其创建过程中提供的API调用,因此实际创建用户只是为了测试它并不理想。

Here's my test: 这是我的测试:

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

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. 因此,显然ActiveRecord错误是由于尝试将模拟用户与期望真实用户关联的配置文件相关联而引起的。

My question is, how do you avoid this kind of problem in writing rails tests? 我的问题是,你如何在编写rails测试时避免这种问题? All I want this test to do is make sure Profile calls :save on it's parent User. 我想要做的测试就是确保Profile调用:保存它的父用户。 Is there a smarter way to do this, or a workaround for the ActiveRecord error? 有没有更聪明的方法来做到这一点,或者ActiveRecord错误的解决方法?

Thanks! 谢谢!

You should be able to use a mock_model for this: 你应该可以使用mock_model

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

I found the only way I was able to get around this problem was to use a Factory user instead of a mock. 我发现我能解决这个问题的唯一方法是使用Factory用户而不是模拟。 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. 这令人沮丧,但在测试两个ActiveRecord模型之间的回调时,您必须使用真实模型,否则保存调用将失败,生命周期将不会发生,并且无法测试回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM