[rspec-users] Can some one please explain why one of those two examples fails?

Mike Mazur mmazur at gmail.com
Sat Mar 17 11:24:47 UTC 2012


Hi,

On Thu, Mar 15, 2012 at 20:46, Mohamad El-Husseini
<husseini.mel at gmail.com> wrote:
> Thanks, Mike. I appreciate the explanation. It's tricky knowing what runs
> when, and what variable is in what scope. It seems like "code smell" to add
> an instance variable to the before block.
>
> I don't understand what advantage one approach has over the other. What
> would you use, the first, that was broken, or the second?

I would probably use `expect`[1]:

  describe "send password reset" do
    let(:user) { FactoryGirl.create(:user) }

    it "generates a unique password_reset_token" do
      expect { user.send_password_reset }.to change(user, :password_reset_token)
    end

    # Or if you want to make sure a token is generated twice
    it "generates a unique password_reset_token each time" do
      user.send_password_reset
      expect { user.send_password_reset }.to change(user, :password_reset_token)
    end

    # or perhaps
    it "generates a unique password_reset_token each time" do
      2.times do
        expect { user.send_password_reset }.to change(user,
:password_reset_token)
      end
    end
  end

Mike


[1]: https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/expect-change


More information about the rspec-users mailing list