Forum: RSpec Using "return" in rspec test

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
768d87a25403cb77f2d5efc4a14f1fa5?d=identicon&s=25 Gary Lin (Guest)
on 2009-05-19 05:03
(Received via mailing list)
Hi,

I am still new to rspec and I wonder if anyone can give me some insight
about the problem I have encountered.  I notice whenever I use "return"
in my test, it will skip all the examples and exit right out of my test
run.  Here is a small example that demonstrate the problem:

describe "This tests uses return in my code" do
  it "should print Hello" do
      puts "Hello"
      # skip some test scenario if product is in demo mode
      if @product.demoMode?
          return;
     else
       # rest of the test goes here.
     end
  end

  it "should print hi" do
      puts "hi"
  end
end

With the above spec, the second "it should print hi" test will never get
executed.
I found it would be very useful to use "return" to skip some of the test
code if a particular scenario occurs.  So I wonder if I cannot use
"return" to achieve this, is there any way I can workaround it?

Thanks,

--Gary
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-05-19 05:44
(Received via mailing list)
Gary Lin wrote:

> describe "This tests uses return in my code" do
>  it "should print Hello" do
>      puts "Hello"         # skip some test scenario if product is in
> demo mode
>      if @product.demoMode?
>          return;

use 'break'

(However, generally speaking, tests should either pass or fail, and they
should
not skip any blocks.)

--
   Phlip
B8c4bfb1b6002a5b43d87de3335401f5?d=identicon&s=25 BJ Clark (Guest)
on 2009-05-19 05:57
(Received via mailing list)
On May 18, 2009, at 7:51 PM, Gary Lin wrote:

>     puts "Hello"         # skip some test scenario if product is in
> end
Gary,
It's better to not have an if/else in a test.

Why not try:

describe "This tests uses return in my code" do

   context "in demo mode" do
     @product.stub!(:demoMode?).and_return(true)
     something.should be_true
   end

   context "not in demo mode" do
     @product.stub!(:demoMode?).and_return(false)
     something.should_not be_true
   end

end

-----
BJ Clark
AboutUs.org
This topic is locked and can not be replied to.