Kainan Zhang Kainan Zhang - 25 days ago 9
Ruby Question

Rspec controller test assign two dimensional Hash fails

i'm trying to run a controller test:
the controller code is

def aix_service_accounts
@no_dn_users= Hash.new
record = 0
@no_dn_users[record]= Hash.new
@no_dn_users[record]['aix_username'] ="abc"
end


The rspec code is

it "should show aix_service_accounts" do
get :aix_service_accounts
expect(assigns(:no_dn_users[0]['aix_username'])).to eq 'abc'
end


The result is


Failures:


1) AixController should show aix_service_accounts
Failure/Error: expect(assigns(:no_dn_users[0]['aix_username'])).to eq 'abc'

expected: "abc"
got: {"marked_for_same_origin_verification"=>true, "no_dn_users"=>{0=>{"aix_username"=>"abc"}}}

(compared using ==)

Diff:
@@ -1,2 +1,3 @@
-"abc"
+"marked_for_same_origin_verification" => true,
+"no_dn_users" => {0=>{"aix_username"=>"abc"}},

# ./spec/controllers/aix_controller_spec.rb:29:in `block (2 levels) in <top (required)>'


Could anyone help and explain the reason to me? Thanks!

Answer

Sure - you're trying to ask for a single key called :no_dn_users[0]['aix_username'] from the assigns. You need to change that to:

assigns(:no_dn_users)[0]['aix_username']

instead.

Ie, get out the first part by the key :no_dn_users, this will be the hash-inside-an-array that you're then referencing using indexing