Rspec Mocking:ActiveRecord :: AssociationTypeMismatch

And*_*rew 7 activerecord rspec ruby-on-rails mocking ruby-on-rails-3

我是Rspec的新手并尝试为用户配置文件设置测试.个人资料belongs_to用户.

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

我正在尝试为此编写一个测试,我正在获得一个ActiveRecord :: AssociationTypeMismatch.原因是我正在使用模拟用户,但我正在尝试测试当Profile更新时它发送:保存到用户.此外,用户模型还有一个电子邮件确认过程以及在其创建过程中提供的API调用,因此实际创建用户只是为了测试它并不理想.

这是我的测试:

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
Run Code Online (Sandbox Code Playgroud)

因此,显然ActiveRecord错误是由于尝试将模拟用户与期望真实用户关联的配置文件相关联而引起的.

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

谢谢!

zet*_*tic 11

你应该可以使用一个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
Run Code Online (Sandbox Code Playgroud)

  • 具体是什么? (2认同)

And*_*rew 4

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