【问题标题】:How do I test this code in RSpec?如何在 RSpec 中测试此代码?
【发布时间】:2012-08-08 14:30:13
【问题描述】:

这是在 Ruby on Rails 3.2.2 中仅通过 ajax 调用的方法

def some_ajax_action
    @user = User.find_by_id(params[:id])
    @user_list = User.find_all_by_parent_id(params[:id])
    respond_to do |format|
      format.js
    end
  end

我想知道是否有必要(或可能)使用 RSpec 对其进行测试?有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    怎么样:

    before do
      User.stub(:find_by_id)
      User.stub(:find_all_by_parent)
    end
    
    it "finds the user" do
      User.should_receive(:find_by_id).with("37")
      xhr <HTTP VERB>, :some_ajax_action, :id => "37"
    end
    
    it "finds the user list" do
      User.should_receive(:find_all_by_parent).with("37")
      xhr <HTTP VERB>, :some_ajax_action, :id => "37"
    end
    

    &lt;HTTP VERB&gt; 替换为routes.rb 中的任何内容,用于这些ajax 调用,例如如果你有

    get 'some_ajax_action'
    

    那么第一个是xhr :get, :some_ajax_action, :id =&gt; "37"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 2013-07-13
      相关资源
      最近更新 更多