rspec 测试书写规范

之前很为写测试头痛,从现在开始测试也要认真写啊 😂 。
总是搞不懂 describe context it let subject before/after 之间先后顺序以及含义。大概看了一下 rspec-style-guide,可以有一定的了解。本文摘自 The RSpec Style Guide,详尽的请参考原文。

完整结构:

class

class Article
  def summary
    #...
  end

  def self.latest
    #...
  end
end  

article_spec.rb

describe Article do
  subject { FactoryGirl.create(:some_article) }
  let(:user) { FactoryGirl.create(:user) }
  
  before do
    # ...
  end

  after do
    # ...
  end
  
  describe '#summary' do
    context 'when there is a summary' do
      it 'returns the summary' do
        # ...
      end
    end
  end
  
  describe '.latest' do
    context 'when latest' do
      it 'returns the latest data' do
        # ...
      end
    end
  end
end

articles_controller_spec.rb

# A classic example for use of contexts in a controller spec is creation or update when the object saves successfully or not.

describe ArticlesController do
  let(:article) { double(Article) }

  describe 'POST create' do
    before { allow(Article).to receive(:new).and_return(article) }

    it 'creates a new article with the given attributes' do
      expect(Article).to receive(:new).with(title: 'The New Article Title').and_return(article)
      post :create, article: { title: 'The New Article Title' }
    end

    it 'saves the article' do
      expect(article).to receive(:save)
      post :create
    end

    context 'when the article saves successfully' do
      before do
        allow(article).to receive(:save).and_return(true)
      end

      it 'sets a flash[:notice] message' do
        post :create
        expect(flash[:notice]).to eq('The article was saved successfully.')
      end

      it 'redirects to the Articles index' do
        post :create
        expect(response).to redirect_to(action: 'index')
      end
    end

    context 'when the article fails to save' do
      before do
        allow(article).to receive(:save).and_return(false)
      end

      it 'assigns @article' do
        post :create
        expect(assigns[:article]).to eq(article)
      end

      it 're-renders the 'new' template' do
        post :create
        expect(response).to render_template('new')
      end
    end
  end
end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是一个简单的关于Rails Rspec的简单的介绍 1 安装Rspec 在Rails的配置文件Gemfile配置...
    AQ王浩阅读 27,129评论 6 28
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,754评论 19 139
  • 话说昨日,健哥让我分享下怎么用rspec写模型的测试,顿时一脸懵逼,因为只会些拳脚猫功夫,赶紧百度谷歌相关知识,七...
    严三金阅读 9,930评论 2 52
  • 原文: https://github.com/ecomfe/spec/blob/master/javascript...
    zock阅读 8,658评论 2 36
  • 加速测试的方法 这里所说的“速度”有两层含义。 其一,当然是测试运行所用的时间。我们这个小程序的测试已经开始出现慢...
    AQ王浩阅读 4,516评论 0 1