Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ActiveRecord::AssociationTypeMismatch #32

Closed
sporto opened this issue Jul 24, 2013 · 1 comment
Closed

ActiveRecord::AssociationTypeMismatch #32

sporto opened this issue Jul 24, 2013 · 1 comment

Comments

@sporto
Copy link

sporto commented Jul 24, 2013

I have the following test:

describe Comment do
    fake(:user) { User }
    let(:comment) { Comment.new(user: user) }

    it "has a user" do
        expect(comment.user).to eq(user)
    end
end

As I am testing comment I don't want it to be a fake, but user I would like to be a fake.

Rspec fails with:

ActiveRecord::AssociationTypeMismatch:
   User(#70251274274320) expected, got User(#70251274343580)

Not sure if this should work or I should try to do things differently. Thanks.

@psyho psyho closed this as completed in e32877f Jul 25, 2013
@psyho
Copy link
Owner

psyho commented Jul 25, 2013

It looks like we had a bug in "Fake#is_a?" which caused the association type mismatch.

However, even if it is possible to pass fakes to AR associations, I would advise against that, because it violates the "don't mock what you don't own" principle.

In order to pass a fake to an AR association, you have to know what AR does with it under the hood, which is (in pseudocode):

def user=(user)
  id_attr = user.primary_key
  id_value = user[id_attr]
  self.user_id = id_value
  @user = user
end

However, when you update your project to use a newer version of AR, this code might change, and all of your tests that depend on that behavior would break.

The way I deal with AR classes in my projects is that I treat them mostly as value types (rule of thumb: no conditionals in AR models). Since value types don't contain any logic, you are free to use them in your isolated tests. Destroy All Software has a lot more on this topic if you are interested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants