Reputation: 10825
I found that stackoverflow old post that suggests model_entity.send(:before_create)
but now it doesn't work. So, how can I test method that should execute before create, update, destroy
.There is another post but i can't figure out, what I should do in my case.
class User < ActiveRecord::Base
before_create do |user|
user.secure_token = UUID.new.generate
end
end
The point is I can just make a method with this code, and call it. Is there any other ways?
In general, if I want to test after_create method, that only have in my model at all, I should create Model Object and check it. But, I guess, it's unnecessary actions. I could just check this method without creation any instances.
Upvotes: 2
Views: 6515
Reputation: 1339
There's a dry way of doing this:
expect{ user.save }.to change{ user.secure_token }
Upvotes: 5
Reputation: 9857
Just found something tricky. If you need to validate the actual result, validate that separately, because the current rspec doesn't pass the return value of the function :secure_token=
if you use the .should_receive(:secure_token=)
. Example:
Model as above:
describe "verifies that secure_token= is called" do
@user = User.new
@user.should_receive(:secure_token=)
@user.save
end
describe "verifies the result is set" do
@user = User.new
@user.save
expect(@user.secure_token).not_to be_empty
end
But if you put the expect not to be empty in the same test as the should_receive, then the test will fail.
Upvotes: 3
Reputation: 890
If you are using rspec, I'm guessing you can do:
@user = User.new
@user.should_receive(:secure_token)
@user.save
Upvotes: 2