Blankman
Blankman

Reputation: 267040

How to properly add context or seperation of unit tests in a single spec file?

Say I have a user_spec.rb file, and I have allot of tests in this file.

How can I add or group together related tests?

I think I read that I can add context, but I am not sure if that is what i am after.

I want to do something like this:

describe User do

  password tests do
     length related tests do
       it "..." do
       end
       it "..." do
       end
     end

     bad characters related tests do
         it "..." do
         end
         it "..." do
         end
     end
  end

end

What is the correct way to do this if it is possible?

Upvotes: 0

Views: 51

Answers (2)

brentvatne
brentvatne

Reputation: 8038

You can use nested describe blocks to group related tests

describe User do

  describe "password tests" do
     describe "length related tests" do
       it "..." do
       end
       it "..." do
       end
     end

     describe "bad characters related tests" do
         it "..." do
         end
         it "..." do
         end
     end
  end

end

Edit: In response to your question: "within each sub-describe block, can I set variables for that scope? but these variables should not be available in any other describe blocks": Within each describe block you create a new scope, meaning that this would work:

describe "password tests" do
    where_i_am = "inside password tests"
    describe "length related tests" do
        #some code
        puts where_i_am #outputs "inside password tests"
    end
end

puts where_i_am #undefined local variable or method ...

Upvotes: 2

David Grayson
David Grayson

Reputation: 87426

I think context is just an alias for decribe, so you should be able to do this:

describe User do
  describe "password" do
    describe "length" do
      it "must be shorter than 400 characters" do
      end
      it "must be longer than 3 character" do
      end
    end

    describe "characters" do
      it "newline is not allowed" do
      end
    end
  end
end

Upvotes: 2

Related Questions