如何期待'='方法运行'会话'?

时间:2011-09-30 11:27:04

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

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

在我的控制器中我有:

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

在相关的spec文件中,我想做类似以下内容:

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

1 个答案:

答案 0 :(得分:3)

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

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

然而,这对我来说真的很有侵略性。不是我永远不会这样做,但我会问你为什么不想只测试结果?

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