Search code examples
ruby-on-railsrspecfactory-botrspec-rails

How to get assigned value when a spec is run in RSpec?


I'm using the FriendlyId gem and it generates a slug when a record is saved. It works great.

I can route to the slug like: places/house-of-dead, perfect. But I'm having a problem when it comes to testing.

I'm using FactoryGirl to stub the parameters that I'm going to create, but I don't know how to get that generated slug to assert if my route redirects to it, my test is below and (???? should be the generated slug).:

    context '#create' do
      it 'should redirect to place after created' do
        place = FactoryGirl.attributes_for(:place)

        post :create, { place: FactoryGirl.attributes_for(:place) }

        response.should redirect_to places_path(slug: ????)
      end
    end

My controller is simple:

def create
    @place = Place.new(params[:place])

    # setting up who owns this place
    @place.user = current_user

    if @place.save
      flash[:success] = "Place created."

      redirect_to @place
    else
      render :new
    end
end

As you can see, I use redirect_to @place and it redirects me to `place/:slug', but when it comes to testing that redirect, how do I do it?

Also, is my testing way right/good?

Thanks.


Solution

  • You almost answered yourself:

    response.should redirect_to places_path(assigns(:place))
    

    or if you need to use the slug:

    response.should redirect_to places_path(slug: assigns(:place).slug)
    

    See https://github.com/rspec/rspec-rails#assigns for more on assigns().

    And this line

    place = FactoryGirl.attributes_for(:place)
    

    is redundant, as you never use the place variable in the rest of your test.