首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最后与规范代码相关的重构

最后与规范代码相关的重构
EN

Stack Overflow用户
提问于 2011-09-28 21:09:34
回答 1查看 118关注 0票数 1

我使用的是Ruby on Rails 3.1.0和rspec-rails 2 gem。我想在我的规范文件中重构以下示例代码:

代码语言:javascript
复制
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 World")
  end
end

我如何重构上面的response.body.should include("Hello World")代码,以便编写更少的代码?也就是说,如何使用一个对两个规范示例都有效的语句来测试response.body内容?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-28 21:19:14

使用shared_examples_for

如下所示:

代码语言:javascript
复制
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

请参阅文档here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7583768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档