hwrd
hwrd

Reputation: 2180

Rspec mock_model not available in instanced object?

I have this code in a model called Project. It sets a owner to a project before the project is saved.

before_save :set_owner

# Set the owner of the project right before it is saved.
def set_owner
  self.owner_id = mock_model(User).id # current_user.id is stubbed out for a mock_model.
  # Lifecycle is set by the form's collection_select
end

And current_user function is stubbed out in my Rspec tests to return a mock_model (which is why the code above is showing mock_model instead of current_user).

Now, when I run this, my Rspec tests break, and complains:

undefined method `mock_model' for #<Project:0x105c70af0>

My guess, is that since before_save is a instance function, it somehow thinks that mock_model is a function defined in Project.

Someone must have encountered this before... Any way around it?

Upvotes: 0

Views: 699

Answers (1)

Peter Brown
Peter Brown

Reputation: 51697

Two things immediately stand out:

  1. You shouldn't be using mock_model in your actual Project model. All test code should remain in the specs.

  2. You cannot pass the current_user object from the controller to the model (at least not in any way you should).

I would use an attr_accessor in your project model to set the current_user id.

class Project < AR::Base
  attr_accessor :current_user

  def set_owner
    self.owner_id = current_user.id unless current_user.nil?
  end
end

Then your spec should look something more along the lines of:

it "should set the owner id" do
  user = mock_model(User)
  project = Project.new
  project.current_user = user
  project.save
  project.owner_id.should == user.id
end

Upvotes: 2

Related Questions