-
-
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 |
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.
Does wrapping each it block in a context/describe fix it?
Are you around in IRC? I see something that looks suspicious, but want to confirm.
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.
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.
This is affecting rspec versions >= 2.10.x, including the most recent release, 2.11.3.