alex
alex

Reputation: 3742

Test controller with rspec - need to stub before_save

I have in User.rb model:

before_save { self.email.downcase! }

and I need to stub this method in users_controller_spec.rb:

User.any_instance.stubs(:before_save_callback_method).returns(true) #doesn't work
User.any_instance.stubs(:valid?).returns(true) #works

How can I do this?

Upvotes: 1

Views: 1398

Answers (3)

arieljuod
arieljuod

Reputation: 15848

do you really need that before_save method? maybe it would be better if you override email=, so the email gets downcased just right after assignment and you have that downcased even before saving the record

User < ActiveRecord
  def email=(value)
    write_attribute(:email, value.downcase)
  end
end

I don't know if that helps for your test, but sometimes that's better than a before_save callback

Upvotes: -1

gerky
gerky

Reputation: 6415

You don't really need to stub out the before_save callback, rather you can stub out methods called by the callback. You can move the behavior to a method and stub that instead.

before_save :downcase_email

def downcase_email
  self.email.downcase!
end

Then in your specs:

user.stub(:downcase_email).and_return(true)

Upvotes: 3

Paritosh Singh
Paritosh Singh

Reputation: 6404

If you are using mock, it can be done like this

describe User
  it "should accept email_downcase before save" do
    user = mock(User)
    user.should_receive(:email_down).and_return(email.downcase) # => use return in case you want to
  end
end

thanks

Upvotes: 1

Related Questions