Richlewis
Richlewis

Reputation: 15384

Rspec Test Error - Undefined method create

Im trying to improve my Rspec tests and write more of them, In this example i can create an image fine and the test passes but i have an issue with deleting that image..

Here is my test so far

describe TimeTable do
  before(:each) do

  Paperclip::Attachment.any_instance.stub(
    :post_process
  ).and_return(true)
  Paperclip::Attachment.any_instance.stub(
    :save
  ).and_return(true)
  # This was a little harder - had to check the stack trace for errors.
  Paperclip::Attachment.any_instance.stub(
    :queue_all_for_delete
  ).and_return([])
end

it 'should save a image for TimeTable' do
  image = Rack::Test::UploadedFile.new(
    'spec/fixtures/rails.png', 'image/png'
  )
  @timetable = TimeTable.new(
    photo: image
  )
  @timetable.save.should eq(true)
  @timetable.photo_file_name.should eq('rails.png')
end

it 'should delete an image for TimeTable' do
  image = Rack::Test::UploadedFile.new(
    'spec/fixtures/rails.png', 'image/png'
  )
  @timetable.create!(
    photo: image
  )
  expect { @timetable.destroy }.to change { TimeTable.count }.by(-1)
end
end

The error/failure i get is

TimeTable should delete an image for TimeTable
 Failure/Error: @timetable.create!(
 NoMethodError:
   undefined method `create!' for nil:NilClass
 # ./spec/models/timetable_spec.rb:33:in `block (2 levels) in <top (required)>'

How do i approach this test to delete the image

Any help appreciated

Upvotes: 0

Views: 436

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53038

Replace

@timetable.create!(
    photo: image
  )

with

@timetable= TimeTable.create!(
    photo: image
  )

create! is a class method not instance method. You are calling it on the instance of TimeTable. Hence, the error.

Upvotes: 3

Related Questions