rspec model spec; testing if local var is assigned

时间:2016-04-15 15:02:45

标签: ruby-on-rails testing rspec model rspec-rails

I'd like to test in my model spec if the local var is set in the method. I tried to use assigns, but it doesn't work in model specs. What is the rails way to do this properly?

user.rb

def decreased_chat_number_pusher
  number = self.new_chat_notification #I wanna test if this is set
  Pusher.trigger_async('private-'+ self.id.to_s, 'new_chat_notification', { number: number })
end

user_spec.rb

  let(:user) { create(:user) }

  it "decreased_chat_number_pusher" do
    user.new_chat_notification = 3
    number = user.new_chat_notification
    #FOLLOWING LINE THROWS UNDEFINED METHOD: ASSIGNS
    expect(assigns(number)).to match(user.new_chat_notification)
    allow(Pusher).to receive(:trigger_async).with(('private-' + user.id.to_s), 'new_chat_notification', {number: number} )
    expect(Pusher).to receive(:trigger_async).with(('private-' + user.id.to_s), 'new_chat_notification', {number: number} )
    user.decreased_chat_number_pusher
  end

1 个答案:

答案 0 :(得分:1)

  

expect(assigns(number))。匹配(user.new_chat_notification)

正如您所发现的,

assigns在模型规范中不起作用。 AFAIK它只在视图规范中可用,甚至在那里它测试实例变量的值,而不是局部变量

局部变量不是断言的好主题,即使您可以使用RSpec进行测试。它是该方法实现的一部分 - 测试应该关注方法的行为

您可以更改方法签名,以便在测试中定义number

def decreased_chat_number_pusher(number=new_chat_notification)

然后您可以测试number的不同值的行为:

expect(decreased_chat_number_pusher).to # succeeds when default value is set
expect(decreased_chat_number_pusher(nil)).to # fails when argument is nil
expect(decreased_chat_number_pusher(:whatever)).to # or pass in any value