8

我正在尝试模拟控制器的会话哈希,如下所示:

it "finds using the session[:company_id]" do
  session.should_receive(:[]).with(:company_id).and_return 100
  Company.should_receive(:find).with(100)
  get 'show'
end

当我调用 get 'show' 时,它指出:

received :[] with unexpected arguments  
expected: (:company_id)  
   got: ("flash")

控制器代码如下所示:

def show
  company_id = session[:company_id]
  @company = Company.find params[company_id]
end

我也简单地尝试过设置

it "finds using the session[:company_id]" do
  session[:company_id]= 100
  Company.should_receive(:find).with(100)
  get 'show'
end

但随后遇到一个问题:

expected: (100)
got: (nil)

任何人都有想法为什么?

4

4 回答 4

5

我刚碰到这个。我无法让 should_receive 不干扰 flash 的东西。

但这让我测试了我正在寻找的行为:

it "should redirect to intended_url if set" do
  request.env['warden'] = double(:authenticate! => true)
  session.stub(:[]).with("flash").and_return double(:sweep => true, :update => true, :[]= => [])
  session.stub(:[]).with(:intended_url).and_return("/users")
  post 'create'
  response.should redirect_to("/users")
end

希望有帮助...

于 2012-02-17T12:36:18.263 回答
3

我不知道如何模拟会话容器本身,但是在大多数情况下,只需通过请求传递会话数据就足够了。所以测试将分为两种情况:

it "returns 404 if company_id is not in session" do
  get :show, {}, {}
  response.status.should == 404 # or assert_raises depending on how you handle 404s
end

it "finds using the session[:company_id]" do
  Company.should_receive(:find).with(100)
  get :show, {}, {:company_id => 100}
end

PS:忘了提到我正在使用这个片段中的一些自定义助手。

于 2013-11-18T10:24:31.807 回答
0

尝试这个:

session.expects(:[]).with(has_entries('company_id' => 100))
于 2012-01-11T19:30:18.430 回答
-1

这是因为您从控制器获取闪存会话。所以定义它。Flash 保存在会话中。

it "finds using the session[:company_id]" do
  session.stub!(:[]).with(:flash)
  session.should_receive(:[]).with(:company_id).and_return 100
  Company.should_receive(:find).with(100)
  get 'show'
end
于 2010-09-12T13:21:17.053 回答