[rspec-devel] Proposal: when_it syntax

Antti Tarvainen antti.tarvainen at iki.fi
Sun Oct 5 05:23:32 EDT 2008


Hello.


I propose a new syntax that helps DRY up specs when using
one-expectation-per-example style. There have been similar proposals
before, but no patches. As far as I know, the idea wasn't killed, just
forgotten.

The patch adds a new "when_it" method and a new parameter to the "it"
method. "When_it" describes the action of the example, allowing "it"
parts to describe only the expectation.

The new parameter to "it" is called :implicitly, and it means that the
expectation should be run before the "when_it" part. (That is, it is a
mock expectation, and regards the implicit interface of the object.)
"It" parts without the :implicitly parameter are run after the
"when_it" part.


Here's an example of the syntax:

describe Controller do
  before(:each) do
    @model = mock("model").as_null_object
    @view = mock("view").as_null_object
    @controller = Controller.new(@model, @view)
  end

  when_it do
    @return_value = @controller.act_on(:some_input)
  end

  it "should get data from model", :implicitly do
    @model.should_receive(:data_for).with(:some_input)
  end

  it "should return :success" do
    @return_value.should == :success
  end
end


For a slightly longer example, see http://tinyurl.com/when-it-example .

What do you think? The new syntax makes specs more DRY, but does it
improve readability?


[patch]
http://github.com/tarvaina/rspec/commits/topic/when_it_in_one_commit
http://github.com/tarvaina/rspec-rails/commits/topic/when_it_compatibility

[one expectation per example]
http://techblog.daveastels.com/2006/08/27/one-expectation-per-example-a-remake-of-one-assertion-per-test/

[old discussions]
http://rubyforge.org/tracker/?func=detail&group_id=797&aid=10285&atid=3152
http://rubyforge.org/pipermail/rspec-users/2007-April/001386.html


Antti


More information about the rspec-devel mailing list