【问题标题】:How to expect that the '=' method runs for the 'session'?如何期望“=”方法为“会话”运行?
【发布时间】:2011-09-30 11:27:03
【问题描述】:

我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2gem。我想测试一些session 数据是否已设置为nil

在我的控制器中,我有:

def create
  ...
  session[:user] = nil
  ...
end

在相关的规范文件中,我想做如下内容:

it "should be set to nil" do
  # Here I would like to expect if the 'session[:user]' is set to 'nil'
  # NOT using this approach:
  #
  #   session[:user].should be_nil
  #
  # That is, I would be sure that the 'session[:user] = nil' runs the same way
  # I may do with method "expectation". For example:
  #
  #   mock_model(User).should_receive(:find).and_return(nil)
  #
  # Maybe a solution can be similar to this (note: of course, the following
  # doesn't work):
  #
  #   session[:user].should_receive(:"=").and_return(nil)

  post :create, { ... }, { ... }

  ...
end

有可能吗?如果有,怎么做?

P.S.:我想使用这种方法来检查一些特定的内部行为。


更新 ...我如何测试以下内容?

session[:user][:nested_key] = nil

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    您正在寻找的方法是[]=

    session.should_receive(:[]=).with(:user, nil)
    

    然而,这对我来说真的很侵入。不是说我永远不会这样做,而是我会质疑你为什么不想只测试结果?

    session[:user] = 37
    post :create # ...
    session[:user].should be_nil
    

    【讨论】:

    • 如果我必须测试以下内容怎么办? session[:user][:nested_key]。 P.S.:你说:“[...] 为什么你不想只测试结果?”这是出于安全原因。
    • OT:嗨,David,你的 RSpec 书的忠实粉丝,只是说“嗨”!
    • 你可以做一些事情,比如让:[] 返回一个模拟对象。或使用stub_chain。但正如@david 所说,我建议只检查结果,因为通常如何设置为nil 并不重要。
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多