[RSpec] LEVEL 1: INTRODUCTION

Install RSpec:

 

 

 

Describe

Lets start writing a specification for the Tweet class. Write a describe block for the Tweet model without any examples inside it.

#tweet.rb


class Tweet
end

Answer:

#tweet_spec.rb

describe Tweet do

end

 

It

Now create a pending test called "can set status".

describe Tweet do
  it "can set status"
  
end

 

Couple of ways to make test pending:

 

Expectation

Now let's write the example. Go ahead and instantiate a tweet, give it the status "Nom nom nom", and test the status has been properly set to this value using an == equality matcher.

复制代码
class Tweet
  attr_accessor :status
 
  def initialize(options={})
    self.status = options[:status]
  end
 
  def public?
    self.status && self.status[0] != "@"                                 
  end
end
复制代码

Answer:

describe Tweet do
  it 'can set status' do
    tweet = Tweet.new
    tweet.status = "Nom nom nom"
    tweet.status.should == "Nom nom nom"
  end
end

 

Matchers

Using a predicate 'be' matcher, make sure that a tweet like "Nom nom nom" (which is not a reply because it doesn't start with an '@' sign) is public.

describe Tweet do
  it 'without a leading @ symbol should be public' do
    tweet = Tweet.new(status: 'Nom nom nom')
    tweet.should be_public
  end
end

 

Comparison Matchers

Finish the example below to ensure that our tweet.status.length is less than or equal to 140 characters. Use a be matcher in your spec.

复制代码
class Tweet
  attr_accessor :status
 
  def initialize(options={})
    self.status = options[:status]
  end
 
  def public?
    self.status && self.status[0] != "@"                                 
  end
 
  def status=(status)
    @status = status ? status[0...140] : status
  end
end
复制代码

Answer:

describe Tweet do
  it 'truncates the status to 140 characters' do
    tweet = Tweet.new(status: 'Nom nom nom' * 100)
    tweet.status.length.should be <= 140
  end
end

 

Predict 'be':

posted @   Zhentiw  阅读(393)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示