Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec / Rails matcher that excepts a model to_be_saved

I want to check if the model was persisted to the DB by the various means available. It looks like all these things defer to .save but I'm curious if there is a better way, perhaps using what Dirty provides?

like image 666
PETER BROWN Avatar asked Feb 26 '11 18:02

PETER BROWN


1 Answers

One way to check if a new record was created:

expect {
  MyModel.do_something_which_should_create_a_record
}.to change(MyModel, :count).by(1)

Or, if you're wanting to check that a value was saved, you could do something like:

my_model.do_something_which_updates_field
my_model.reload.field.should == "expected value"

Or you could use expect and change again:

my_model = MyModel.find(1)
expect {
  my_model.do_something
}.to change { my_model.field }.from("old value").to("expected value")

Is that what you were meaning?

like image 135
idlefingers Avatar answered Sep 23 '22 02:09

idlefingers