Testing a sessions decorator lib in ruby on rails with rspec
I have this code in lib/user_session.rb
Its used by one of my controllers via include UserSession.
How can I test it? I've added tests in spec/lib/user_session.rb but the code relies on the session which I'm not sure how to mock.
module UserSession
def viewed
session[:viewed] ||= Array.new
return session[:viewed]
end
def viewed_add(id, name)
if viewed.select{|b| b[:id] == id}.empty?
session[:viewed] << {:id => id, :name => name}
end
return session[:viewed]
end
def viewed_delete(id)
unless id.nil?
session[:viewed].delete_if{|b| b[:id] == id}
return session[:viewed]
end
end
end
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(2)

As far as I can see from your code, you don't rely on the session so much as you rely on an object that conforms to a basic interface in the form of a bracket reader.
Now, I don't use RSpec myself so I couldn't say exactly how to use it in this scenario, but I'd create a mock class with a bracket reader instance method, or even a hash and then test against that object, e.g.
fake_session = { :viewer => nil }
class << fake_session
include UserSession
end
assert_equal [], fake_session.viewer
Hope that helps.
发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。