Search code examples
ruby-on-railsrubyrspecrspec-rails

How to test initialization values of new action with RSpec?


In my Ruby on Rails app I have an action copy that copies an invoice and renders its values to the frontend in a new action.

It works but I am finding it hard to test:

describe 'GET #copy' do

  before :each do
    @invoice = FactoryGirl.create(:invoice, :date => Date.yesterday)
  end

  it "renders the :new template" do # this works
    get :copy, :id => @invoice
    expect(response).to render_template :new
  end

  it "sets the correct date" do
    get :copy, :id => @invoice
    expect(new_invoice.date).to eql(@invoice.date) # what I had in mind...
  end

end

I would simply like to test if the date gets copied correctly and is shown in the form. Will I have to save the new invoice first in order to test that?

Thanks for any help.


Solution

  • class YourController < ApplicationController
      def copy
       @new_invoice
      end
    end
    

    Use assigns for testing instance variables inside your controller, like that expect(assigns(:new_invoice).date).to eql(@invoice.date) For latest RSpec version, need install gem 'rails-controller-testing' for using assigns method