Skip to content

Instantly share code, notes, and snippets.

@ajsharp
Created September 26, 2012 19:03
Show Gist options
  • Select an option

  • Save ajsharp/3789895 to your computer and use it in GitHub Desktop.

Select an option

Save ajsharp/3789895 to your computer and use it in GitHub Desktop.
class PostsController
def create
post = Post.new params[:post]
if post.save
render status: 201, text: ''
else
render status: 422, text: ''
end
end
end
describe PostsController, "POST /create" do
it "returns 422 on failure" do
Post.any_instance.stub(:valid? => false)
post :create
response.status.should == 422
end
end
describe PostsController, "POST /create" do
# Assuming this spec runs after the previous spec, this will fail,
# because the stub on the previous spec carries over
it "returns 200 on success" do
post :create, post: {title: 'hey'}
response.status.should == 201 # this fails due to the global stub
end
end
@ajsharp

ajsharp commented Sep 26, 2012

Copy link
Copy Markdown
Author

This is affecting rspec versions >= 2.10.x, including the most recent release, 2.11.3.

@ajsharp

ajsharp commented Sep 26, 2012

Copy link
Copy Markdown
Author

What's happening here is the that stub created on line 15 is not being destroyed after that example has run. It remains for the remainder for at least the remainder of the runtime, and presumably the remainder of the runtime.

@ian

ian commented Sep 26, 2012

Copy link
Copy Markdown

Does wrapping each it block in a context/describe fix it?

@alindeman

Copy link
Copy Markdown

Are you around in IRC? I see something that looks suspicious, but want to confirm.

@alindeman

Copy link
Copy Markdown

What I'm seeing is this:

post :create, {title: 'hey'}

# Seems like it might need to be:
post :create, post: {title: 'hey'}

I'm trying to rule out that post really isn't invalid based on the real implementation of valid?. Right now, the second spec is effectively doing Post.new(nil) because params[:post] is nil.

@ajsharp

ajsharp commented Sep 27, 2012

Copy link
Copy Markdown
Author

I apologize for creating such an initial contrived example -- I've updated the gist to more accurately reflect the behavior we're seeing. Basically, a .any_instance stub in a completely separate top-level describe block is carrying over to the other one. I've verified this by observing the validation failure error in the specs, then commenting out the seemingly unrelated describe block that has the any_instance stub, running the spec again, and the example passes.

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