0

I've looked around several questions on SO and can't find exactly what I'm looking for.

I have a simple rails controller. with a new method and private method:

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

How do I properly test the new method, and should I be testing the load_bar method? I'm currently doing the following, but it doesn't feel quite right:

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

1 Answer 1

0

Something like that is enough to test this action:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Seems easy enough. I thought I might be overthinking it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.