开发者

two shoulds in one rspec block

I am trying out RSpec with a little tic tac toe game. so far I have this spec

require './tic_tac_toe'

describe TicTacToe do
  subject { TicTacToe.new }

  context "when starting a new game" do
    its(:grid) { should have(9).cells }
    its(:grid) { should be_empty }
  end
end

this works just fine, but the output is like this (grid shows up two times for one test each) I would like it to show both tests under one grid.

TicTacToe
  when starting a new game
    grid
      should have 9 cells
    grid
      should be empty

can I write something like this?

its(:grid) { should have(9).cells and should be_empty }

or something like this?

its(:grid) { should have(9).cells and its(:cells) { should be_empty} }

thanks!


EDIT:

I did what I want using this 
context "when starting a new game" do
    describe "grid" do
      subject { @game.grid }
      it "should have 9 empty cells" do
        should have(9).cells
        should be_empty
 开发者_运维知识库     end
    end
  end

is there a better way to do this, using the its() method?


An its is equivalent to a describe and an it, so I don't think so. You could explicitly write it out like this:

describe TicTacToe do
  subject { TicTacToe.new.grid }

  context "when starting a new game" do
    describe "grid" do
      it { should have(9).cells}
      it { should be_empty}
    end
  end
end

I'm a little confused by the spec though, it has 9 cells and is also empty? So I'm not sure this is what you want exactly but the output will be:

TicTacToe
  when starting a new game
    grid
      should have 9 cells
      should be empty


This is one way to do what I want.. not using its(), but it's the output I want.

context "when starting a new game" do
    describe "grid" do
      subject { @game.grid }
      it "should have 9 empty cells" do
        should have(9).cells
        should be_empty
      end
    end
  end


You could but I recommend you shouldn't and here's why:

Currently this:

context "when starting a new game" do
  its(:grid) { should have(9).cells }
  its(:grid) { should be_empty }
end

will check for the grid having 9 cells and report on that. It will then separately see if the grid is empty.

This will report correctly on conditions such as:

A grid with 9 elements that is empty with => true, true
A grid with 8 elements that is empty with => false,true
A grid with 9 elements that is not empty with => true, false
A grid with 8 elements that is not empty with => false, false

However if you put the conditions together then for the above you'll get single returns such as

=> true
=> false
=> false
=> false

which is not so informatiuve for the falses as you wouldn't have the distinction of which part is false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜