Testing a sessions decorator lib in ruby on rails with rspec

Testing a sessions decorator lib in ruby on rails with rspec

坐在坟头思考人生 发布于 2021-11-28 字数 706 浏览 881 回复 2 原文

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

别想她 2022-06-07 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.

山人契 2022-06-07 1 楼

You need to mock or stub the [] operator on the session. For example, in your spec, you can do:

session.stub!(:[]).and_return "foo"

or

session.should_receive(:[]).with(:viewed)