【问题标题】:Testing rails controller with nested resource and private method with rspec使用 rspec 测试具有嵌套资源和私有方法的 Rails 控制器
【发布时间】:2014-03-17 04:30:57
【问题描述】:

我已经查看了几个关于 SO 的问题,但找不到我正在寻找的确切内容。

我有一个简单的 Rails 控制器。使用新方法和私有方法:

class FooController < ApplicationController
  before_action :load_bar

  def new
    @foo = @bar.foos.build
  end

  private

  def load_bar
    @bar = Bar.find params[:bar_id]
  end
end

如何正确测试新方法,我应该测试 load_bar 方法吗?我目前正在执行以下操作,但感觉不太对:

describe FooController do
  let(:bar) { create(:bar) }

  context 'GET new' do
    let(:foo) { mock_model(Foo) }

    it 'should assign a @foo' do
      Bar.should_receive(:find).and_return(bar)
      bar.stub_chain(:foos, :build).and_return(foo)

      get :new, bar_id: bar
      assigns(:foo).should == foo
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    类似的东西足以测试这个动作:

    describe FooController do
      describe "GET 'new'" do
        let(:bar) { create :bar }
    
        it "assigns bar" do
          get :new, bar_id: bar.to_param # Or bar.id
          expect(assigns[:bar]).to eq(bar)
        end
        it "assigns a new foo" do
          get :new, bar_id: bar.to_param
          expect(assigns[:foo]).to be_a_new(Foo)
        end
      end
    end
    

    【讨论】:

    • 看起来很简单。我想我可能想多了。
    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多