home articles newsletter

Enough RSpec

How to force the user as the serializer’s scope:

  # spec/serializers/book_serializer_spec.rb

  RSpec.describe BookSerializer do
    subject(:serialized_book) { serialize(book, scope: user) }

    let(:user) { create :user }
    let(:book) { ... }

    # test stuff

Based on how you define the it part, different behaviors are to be expected:

  # spec/serializers/things_controller_spec.rb

  RSpec.describe ThingsController do
    subject { post :create, params: params }

    # Implicitly calls subject
    it { is_expected.to redirect_to(thing_path(Thing.last)) }

    # Explicitly call subject
    it "redirects to the new thing's show" do
      expect(subject).to redirect_to(thing_path(Thing.last))

    # Does not call subject
    # For this test to work, a before { subject } is needed
    it 'has correct flash message' do
      expect(flash[:notice]).to eq "The thing has been created."