【问题标题】:rspec rails mocking session hashrspec rails 模拟会话哈希
【发布时间】:2010-09-12 03:54:23
【问题描述】:

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

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)

有人知道为什么吗?

【问题讨论】:

标签: ruby-on-rails rspec rspec2


【解决方案1】:

我刚碰到这个。我无法让 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

希望对您有所帮助...

【讨论】:

    【解决方案2】:

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

    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:忘了说我正在使用来自this snippet 的一些自定义助手。

    【讨论】:

      【解决方案3】:

      试试这个:

      session.expects(:[]).with(has_entries('company_id' => 100))
      

      【讨论】:

        【解决方案4】:

        这是因为您从控制器获取 Flash 会话。所以定义它。 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
        

        【讨论】:

        • 我试过了,但还是报错 1) CompanyController GET 'show' finds using the session[:company_id] Failure/Error: get 'show' undefined method sweep' for nil:NilClass # /Users/adam/.rvm/gems/ruby-1.8.7-p299/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:in method_missing'...
        • session 变量在发出请求 (get) 之前不可用。这行不通。
        猜你喜欢
        • 1970-01-01
        • 2020-08-31
        • 1970-01-01
        • 2018-04-09
        • 1970-01-01
        • 1970-01-01
        • 2014-09-11
        • 2016-11-27
        • 2023-03-24
        相关资源
        最近更新 更多