我的 Rails 2 应用程序通过flickraw库显示来自 Flickr 的照片的幻灯片。我的代码有效,但我坚持如何正确编写 RSpec 单元测试。
我有一个Slide
类,它封装了我的应用程序需要从 flickraw 获得的所有内容。它有点像模型对象,但不使用 ActiveRecord。它没有做太多的工作;它将大部分繁重的工作委托给了 flickraw。
我还没有完成测试,因为就像现在一样,它们要求我在 Flickr 的一些照片 ID 中进行硬编码,如果我重新排列照片集或添加新照片,测试就会中断。
所以我所谓的单元测试更像是集成测试。我了解如何使用 RSpec 编写模拟或存根,但不知道如何对 flickraw 库执行此操作。 如何存根 flickraw 并将其转换为单元测试?
幻灯片.rb:
require 'flickraw'
FlickRaw.api_key = "xxx"
FlickRaw.shared_secret = "yyy"
flickr.auth.checkToken :auth_token => "zzz"
PHOTOSET_ID = 123123123
class Slide
attr_accessor :id, :previous_id, :next_id, :url_square, :url_thumbnail, :url_small, :url_medium500,
:url_medium640, :url_large, :url_original
def self.last
photoset = flickr.photosets.getPhotos(:photoset_id => PHOTOSET_ID)
Slide.new(photoset.photo.last.id)
end
def self.first
photoset = flickr.photosets.getPhotos(:photoset_id => PHOTOSET_ID)
Slide.new(photoset.photo.first.id)
end
def self.find(id)
Slide.new(id)
end
def initialize(id)
self.id = id
photo = flickr.photos.getInfo(:photo_id => id)
context = flickr.photosets.getContext(:photoset_id => PHOTOSET_ID, :photo_id => id)
sizes = flickr.photos.getSizes(:photo_id => id)
self.previous_id = (context.prevphoto.id == 0) ? nil : context.prevphoto.id
self.next_id = (context.nextphoto.id == 0) ? nil : context.nextphoto.id
sizes.each do |size|
if size.label == "Square"
self.url_square = size.source
elsif size.label == "Thumbnail"
self.url_thumbnail = size.source
elsif size.label == "Small"
self.url_small = size.source
elsif size.label == "Medium"
self.url_medium500 = size.source
elsif size.label == "Medium 640"
self.url_medium640 = size.source
elsif size.label == "Large"
self.url_large = size.source
elsif size.label == "Original"
self.url_original = size.source
end
end
end
end
幻灯片规格.rb:
require 'spec_helper'
describe Slide do
before(:each) do
first_photo_id = "444555666"
@slide = Slide.new(first_photo_id)
end
describe "urls" do
it "should generate the thumbnail url" do
@slide.url_thumbnail.should match(/_t.jpg$/)
end
it "should generate the small url" do
@slide.url_small.should match(/_m.jpg$/)
end
it "should generate the medium500 url" do
@slide.url_medium500.should match(/.jpg$/)
end
it "should generate the medium640 url" do
@slide.url_medium640.should match(/_z.jpg$/)
end
it "should generate the large url" do
@slide.url_large.should match(/_b.jpg$/)
end
it "should generate the original url" do
@slide.url_original.should match(/_o.jpg$/)
end
end
describe "finding" do
it "should find the correct last photo" do
# ???
end
it "should find the correct first photo" do
# ???
end
end
describe "context" do
it "should return the correct previous photo" do
# ???
end
it "should return the correct next photo" do
# ???
end
end
end