Skip to content

Instantly share code, notes, and snippets.

@mmmries
Created June 13, 2013 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmmries/5777434 to your computer and use it in GitHub Desktop.
Save mmmries/5777434 to your computer and use it in GitHub Desktop.
rspec test that a request makes certain changes to a model. How can I do something like this?
describe "my request" do
it "should update the model" do
Model.any_instance.should_receive(:save) do
self.changes.should include(:attribute)
self.attribute.should == 'value'
end
xhr :put, model_path(model), {attribute: 'value'}
end
end
@localshred
Copy link

So, I would stub out the find call to the model and return an object that the test controls, then use an "expect to change" assertion on the attribute in question.

describe "my request" do
  let(:my_model) { Model.new }
  it "should update the model" do
    Model.should_receive(:find).and_return(my_model)

    expect {
      xhr :put, model_path(model), {attribute: 'value'}
    }.to change { my_model.attribute }.to('value')
  end
end

@mmmries
Copy link
Author

mmmries commented Jun 14, 2013

I like that a lot. Having a direct reference to the object means I can easily assert a lot of things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment