0

I have an instance method that would be invoked after creating a new instance of the class.

How do I test it in Rspec? I use the following and get an error:

  let(:schedule) { ScheduleKaya.new('test-client-id') }
  let(:schedule) { schedule.create_recurring_event('test-keyword', 'slack') }

In other words, I want to create the instance. Then I want to apply a method create_recurring_event.

My test wants to check if it assigned the variables to the instance.

it "has @keyword = test-keyword" do

     expect(schedule.keyword).to eq('test-keyword')

end

Because it makes a database call, I want to check the response back from the call to see if I get a status = 200.

But I can't seem to both create the instance and then apply the method.

Question:

What is the right way to test for an instance method, one that is applied after creating a new instance.

2 Answers 2

1

A let block acts like a method and returns the return value of the last statement. Therefore just write both into the same block and ensure that the right value is returned:

let(:schedule) do
  schedule_kaya = ScheduleKaya.new('test-client-id')
  schedule_kaya.create_recurring_event('test-keyword', 'slack')
  schedule_kaya
end

Or you can use tap:

let(:schedule) do
  ScheduleKaya.new('test-client-id').tap do |schedule_kaya|
    schedule_kaya.create_recurring_event('test-keyword', 'slack')
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Ahhh this is what I was looking for.
This is the first time I saw someone explain this this clearly after scouring the web on every article on rspec and let.
0

I suggest FactoryGirl together with Rspec, if you are on Railsfactory_girl_rails, looks like below:

it "has @keyword = test-keyword" do
  schedule = Factory(:shcedule, keyword: "has @keyword = test-keyword")
  expect(schedule.keyword).to eq('test-keyword')
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.