开发者

Refactoring spec code related at the end

I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I would like to refactor the following sample code in a my spec file:

describe "Making things" do
  it "should make a thing" do
    # Make the thing
    ...

    # This is the same statement as that present in the "should make another
    # thing" example (read below for more information)
    response.body.should include("Hello World")
  end

  it "should make another thing" do
    # Make another thing
    ...

    # The same statement as that present in the "should make a thing" example
    response.body.should include("Hello Wo开发者_如何转开发rld")
  end
end

How can I refactor the above response.body.should include("Hello World") code so to write less code? That is, how can I test the response.body content by using one statement valid for both spec examples?


Use shared_examples_for.

Like this:

describe "Making things" do
  before do
    @user.new
  end

  shared_examples_for "normal case" do
    it "shows hello world" do
      response.body.should include("Hello World")
    end

    # more tests could be here

  end

  context "making a thing" do
    before(:each) do
      # make thing
    end
    it_should_behave_like_a "normal case"          
  end

  context "making another thing" do
    before(:each) do
      # make another thing
    end
    it_should_behave_like_a "normal case"          
  end
end

See documentation here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜