2011-09-30 34 views
3

我正在使用Ruby on Rails 3.1.0和rspec-rails 2 gem。我想测试一些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.:我想用这种方法来检查一些特定的内部行为。


UPDATE ...我如何测试以下?

session[:user][:nested_key] = nil 

回答

3

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

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

这感觉真的侵入到我,但是。不是我永远不会这样做,但我会质疑为什么你不想仅仅测试结果?

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

如果我必须测试类似以下内容,该怎么办? '会话[:用户] [:nested_key]'。 P.S .:你说过:“[...]为什么你不想测试结果?”这是出于安全原因。 – Backo

+0

OT:大卫,你RSpec书的大粉丝,只是说'嗨'! –

+0

@David Chelimsky - 我更新了问题。 – Backo