rspec / rspec-rails

RSpec for Rails 6+
https://rspec.info
MIT License
5.15k stars 1.03k forks source link

mock_model needs base_class? #606

Closed avit closed 12 years ago

avit commented 12 years ago

In my specs I tried using a mock_model for checking ActiveRecord validation. The error I got was:

undefined method `base_class' for Dummy:Class

I assume this is an ActiveRecord class method. Should this be something that a mock_model responds to?

dchelimsky commented 12 years ago

You want stub_model, not mock_model:

http://rubydoc.info/gems/rspec-rails/RSpec/Rails/Mocks:stub_model http://rubydoc.info/gems/rspec-rails/RSpec/Rails/Mocks:mock_model

avit commented 12 years ago

stub_model requires an existing class... Am I missing something?

# this works:
model = mock_model("Dummy", id: 123)
model.class.stub!(base_class: model.class)
Calendar.new(schedulable: model).should be_valid

mock_model's generated class already responds to :primary_key for the name of the model's id column, :base_class might be needed to satisfy both id and type for polymorphic associations...

dchelimsky commented 12 years ago

I have very mixed feelings about this. See #435 for background.

There are two problems: first, the names stub_model and mock_model don't really convey the underlying intent to support ActiveModel API's exclusively with mock_model. The second is that this appears to be the second time that a change in Rails has resulted in the need to change mock_model because something is calling ActiveRecord APIs.

What if you could pass a String to stub_model and we build up a temp ActiveRecord class for you instead?

avit commented 12 years ago

What if you could pass a String to stub_model and we build up a temp ActiveRecord class for you instead?

:thumbsup: That's what I thought the intent was. Agreed on mock_model vs. stub_model being confusing: but this being rspec-rails, I had assumed an instance of a "rails generate model" (i.e. an ActiveRecord double) rather than an ActiveModel.

alindeman commented 12 years ago

@dchelimsky, do you mean that stub_model would act like mock_model if given a String?

dchelimsky commented 12 years ago

@alindeman in terms of whether it uses a real class or generates one, yes, but it would still generate an ActiveRecord::Base subclass, whereas mock_model would continue to generate an ActiveModel.