Search code examples
ruby-on-rails-3rspec-rails

How to put in some data before my rspec test


Im testing a create method on my controller. The creation of the new entity requires another entity already exist in the database. So i need the foreign key before I can insert anything. I have tried

job = Job.create(:client_id => 1, :title => "Title", :date => Time.now, 
   :number_of_workers => 10, :venue => "Somewhere")

  let(:valid_attributes) {
    {
      worker_id: 1,
      job_id: 1,
      salary: 120.0
    }
  }

  let(:valid_session) { {} }

  describe "GET index" do
    it "assigns all hours ad @hours" do
      hour = Hour.create! valid_attributes
      get :index, {}, valid_session
      expect(assigns(:hours)).to eq([hour])
    end
  end

This works but it breaks another test since my Jobs table is now populated. How can I can I create this job in only this test? (I looked at database_cleaner gem but I like to avoid that)

I tried moving the creation of the job into the for each group but then the variable is not accessible.


Solution

  • Doh! use instance variables and put them inside the before loop like this:

    before(:each) do
        http_login
    
        @job = Job.create(:client_id => 1, :title => "Title", :date => Time.now, :number_of_workers => 10, :venue => "Somewhere")
      end
    

    I guess it is all in a transaction then