2016-04-30 43 views
1

我试图让@user.stripe_customer_id返回一个字符串。如果它没有设置,那么它应该运行一个外部服务的调用,设置它并返回它。Rails:如何通过调用它来设置属性

更冗长这里是我的测试:

context 'Stripe ID' do 
    it 'should not be writable' do 
    expect { @user.stripe_customer_id = 'random_id_123123' } 
     .to raise_error(NoMethodError) 
    end 

    it 'should be generated if it does not exist' do 
    @user.save 
    expect(@user.stripe_customer_id).to include('cus') 
    end 
end 

其中@user是一个有效的User << ActiveRecord实例。

Rspec的失败与以下:

Failed examples: 

rspec ./spec/models/user_spec.rb:87 # User Stripe ID should be generated if it does not exist 

而且User.rb文件具有以下行:

def stripe_customer_id 
    if stripe_customer_id.blank? 
     stripe = Stripe::Customer.create(
     description: "Username: #{username}", 
     email: email 
    ) 
     self.stripe_customer_id = stripe.id 
     save! 
    end 
    stripe_customer_id 
    end 

    private 

    def stripe_customer_id=(new_customer_id) 
    write_attribute(:stripe_customer_id, new_customer_id) 
    end 

回答

1

您试图覆盖getter方法为stripe_customer_id

def stripe_customer_id 
    self[:stripe_customer_id] || write_attribute(:stripe_customer_id, new_customer_id) 
end 

这是我刚写下来的一个未经测试的代码。但我很确定这应该适用于你的情况。请试试看,让我知道。

+0

通过它!谢谢! – amingilani

+0

但是,我很好奇,为什么我的版本没有工作? – amingilani

+0

你已经定义了'stripe_customer_id ='这是一个setter方法,用于设置值而不是它们。 :) – Alfie

相关问题