我有一个控制器动作,我想测试一些实例变量,这是我的动作代码:
def index
@users_list = get_response('accounts/by_tag/QuickcallAdmin')['users'].to_a
@credit_admin = !@users_list.select{|h| h['email'] == current_user.email}.blank?
@accounts_emails = Account.pluck(:email)
end
和规范代码:
describe 'GET #index' do
login_user
let(:account) {create(:account)}
it 'responds with 200' do
get :index, :format => :html
controller.instance_variable_set(:@users_list, [{"id"=>2, "email"=>"tes1@test.com", "tenant_id"=>1,"first_name"=>"valera","last_name"=>"rotari","phone_number"=>"89439438954", "tags"=>[{"name"=>"Program", "value"=>"my_company"}, {"name"=>"ProgramAdmin", "value"=>"new_program"}, {"name"=>"ProgramAdmin", "value"=>"new_program1"}, {"name"=>"QuickcallAdmin", "value"=>"q1"}, {"name"=>"CreditAdmin", "value"=>"q1"}]}])
expect(assigns(:credit_admin)).to eql(true)
expect(assigns(:accounts_emails)).to eql(["tes1@test.com"])
end
end
因此你可以看到我尝试分配一些我通常从api调用的响应中得到的哈希值,之后看看credit_admin和account_emails vars是否具有正确的值。问题是如果我在var赋值之后推出一些put in spec我看到我的值已分配,但测试失败,因为credit admin变量为false并且预期为true。我得到了相同的代码,并把它作为rails控制台为自己做一个测试,注意我使用相同的哈希,我有正确的真值。所以似乎@users_list var没有正确分配或类似的东西。另外@account_email是空数组,但是我有从工厂创建的帐号,所以它应该有一些值,看起来像是两者的常见问题
答案 0 :(得分:2)
所以我以另一种方式做到了,将我的规范代码更改为
describe 'GET #index' do
login_user
it 'responds with 200' do
create(:account)
allow(controller).to receive(:get_response).and_return({"users" => [{"id"=>2, "email"=>"tes1@test.com","tenant_id"=>1,"first_name"=>"valera","last_name"=>"rotari","phone_number"=>"89439438954","tags"=>[{"name"=>"Program", "value"=>"my_company"}, {"name"=>"ProgramAdmin", "value"=>"new_program"}, {"name"=>"ProgramAdmin", "value"=>"new_program1"}, {"name"=>"QuickcallAdmin", "value"=>"q1"}, {"name"=>"CreditAdmin", "value"=>"q1"}]}]})
get :index, :format => :html
expect(assigns(:credit_admin)).to eql(true)
expect(assigns(:accounts_emails)).to eql(["tes1@test.com"])
end
end