2022-09-26

rspec: test array of instances

I'm trying to create rspec tests to test an array of instances. Specifically, I want to verify certain attributes of each instance within the array. Is there a way to use rspec to test this scenario?

For example, suppose I have the following array that I want to verify:

[#<Car id:1, buy_date: "2022-10-10", model: "Ford">, 
 #<Car id:2, buy_date: "2021-01-10", model: "Ferrari">, 
 #<Car id:3, buy_date: "2022-03-12", model: "Toyota">]

As my test, I want to check that the buy_date is correct. I tried the following expect statement but I don't think it's meant for arrays of instances so the tests failed when I expected them to pass.

expect(cars).to include([
                have_attributes(
                    buy_date: "2022-10-10"
                ),
                have_attributes(
                    buy_date: "2021-01-10"                   
                ),
                have_attributes(
                    buy_date: "2022-03-12"
                )
            ])

I've also tried it with match_array instead of include but the result was the same.

Any ideas how to use rspec to accomplish this?



No comments:

Post a Comment