ruby-on-rails – 为rspec规范添加辅助函数的正确方法

所以我需要一个辅助函数来创建“未处理的推文”,类似于我从Twitter API gem中获得它们的方式,因此我可以在某些条件下测试我的模型功能.

为此,我在对象describe中添加一个辅助函数,如下所示:

describe Tag,:type => :model do 
# Helpers
    ###
    def unprocessed_tweets(count,name,start_date,end_date)
        tweets = []

        count.times do |index|
            tweet = OpenStruct.new

            tweet.favorite_count = "3"
            tweet.filter_level = "high"
            tweet.retweet_count = "12" 
            tweet.text = "#{name}"

            if index == 0
                tweet.created_at = start_date
            elsif index == (count-1)
                tweet.created_at = end_date
            else
                tweet.created_at = start_date
            end

            tweets.push tweet
        end

        tweets
    end

我还添加了一项测试,以确保我的助手按照我的预期进行长期工作:

it "has a helper for generated unprocessed tweets" do 

        tag_name = "justin"
        start_date = '2015-09-12 2:31:32 0'
        end_date = '2015-09-13 2:31:32 0'

        tweets = unprocessed_tweets(3,tag_name,end_date)

        expect(tweets.size).to eq 3
        expect(tweets.first.favorite_count).to eq "3"
        expect(tweets.first.created_at).to eq start_date
        expect(tweets.last.created_at).to eq end_date
        expect(tweets.last.text).to eq tag_name
    end

这是最好的做法吗?

解决方法

您可以在spec / support中创建一个名为tweet_helpers.rb的新文件,并将其放入其中:
module TweetHelpers
  def unprocessed_tweets(count,end_date)
    tweets = []

    count.times do |index|
      tweet = OpenStruct.new

      tweet.favorite_count = "3"
      tweet.filter_level = "high"
      tweet.retweet_count = "12"
      tweet.text = "#{name}"

      if index == 0
        tweet.created_at = start_date
      elsif index == (count-1)
        tweet.created_at = end_date
      else
        tweet.created_at = start_date
      end

      tweets.push tweet
    end

    tweets
  end
end

您的spec测试文件应如下所示:

require './spec/support/tweet_helpers'

RSpec.configure do |c|
  c.include TweetHelpers
end

RSpec.describe "an example group" do
  it "has a helper for generated unprocessed tweets" do

    tag_name = "justin"
    start_date = '2015-09-12 2:31:32 0'
    end_date = '2015-09-13 2:31:32 0'

    tweets = unprocessed_tweets(3,end_date)

    expect(tweets.size).to eq 3
    expect(tweets.first.favorite_count).to eq "3"
    expect(tweets.first.created_at).to eq start_date
    expect(tweets.last.created_at).to eq end_date
    expect(tweets.last.text).to eq tag_name
  end
end

我认为在单独的模块中定义辅助方法而不是拥挤规范测试文件本身是一种很好的做法.

有关更多信息和示例,请参见this.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...