mr_muscle
mr_muscle

Reputation: 2910

How to update rails rspec nasted let attribute

I want to change attribute inside previously defined let to make my test works. I know it is hash in hash but none of my solutions works.

I've got several similar let but which looked like this

let(:second_data) do
  {
    'id' => second.id.to_s,
    'type' => 'account',
    'attributes' =>
     {
       'status' => 'new',
       'created_at' => second.created_at.as_json,
       'time_information' => second.credit.process.date_of_interest.as_json
     }
   }
end

At the end these lets are merged to one

let(:json_serialized_offers) do
  {
    'data' => [first_data, second_data, third_data],
    'included' => first_included + second_included + third_included
  }
end

Now I want to change status to expired in second_data which is nested in section data in :json_serialized_offers (as you see above).

I was trying to declere it once again, in right context, by

context "when status 'closed' passed " do
            let(:json_serialized_offers) do
              {
                'data' => second_data { status: 'expire' }
              }
            end
            # some logic
          end

But nothing changed, is it possible to do so?

Upvotes: 3

Views: 2838

Answers (1)

Glyoko
Glyoko

Reputation: 2080

Just use a another "let" to set the status attribute.

Create a :status variable with a new let and change your first let like so:

let(:status) { 'new' } # <==== new let

let(:second_data) do
  {
    'id' => second.id.to_s,
    'type' => 'account',
    'attributes' =>
     {
       'status' => status # <==== set status using new variable
       'created_at' => second.created_at.as_json,
       'time_information' => second.credit.process.date_of_interest.as_json
     }
   }
end

Then, in the context where you need to change it, just redefine :status.

context "when status 'closed' passed " do
  let(:status) { 'expired' }
  it ...
end

This will redefine :status within this context, and will also change the status attribute in :second_data.

This strategy is great for setting deeply nested attributes, and it also makes it so that you only have to redefine the things that changed.

Upvotes: 7

Related Questions