rspec测试getter和setter方法

时间:2016-04-15 17:52:29

标签: ruby-on-rails testing rspec getter-setter

task.rb

#executor (user class) has one profile and has many tasks.

def task_name_company
  [executor.try(:profile).try(:first_name), executor.try(:profile).try(:last_name), executor.try(:profile).try(:company)].join(' ')
end

def task_name_company=(name)
  self.executor = User.joins(:profile).where("CONCAT_WS(' ', first_name, last_name, company) LIKE ?", "%#{name}%").first if name.present?
rescue ArgumentError
  self.executor = nil
end

task_spec.rb

let(:task) = { create(:task) }
let(:user) = { create(:user) }
let(:profile = { create(:profile) }


# I tested the getter like this and seems to be working
it "task_name_company getter" do
  task.executor.profile = profile
  expect(task.task_name_company).to eq("John Doe ABC Inc")
end

# I don't know how to test the setter method

it "task_name_company setter" do
end

让我们获得最新消息!

user.rb

def decrease_new_chat_notifications
  decrement!(:new_chat_notification) if self.new_chat_notification > 0
end

def decreasing_post_notification_number(post_id)
  notifications.this_post_comments(post_id).unchecked.each do |notification|
    checking_and_decreasing_notification(notification)
  end
end

user_spec.rb

let(:user) { create(:user) }
let(:post_notification) { create(:notification, notifiable_type: "Post", recipient: user, sender: sender, checked_at: nil, notifiable_id: post.id)}

it "decrease_new_chat_notifications if greater than 0" do
  user.new_chat_notification = 1
  expect{user.decrease_new_chat_notifications}.to change{user.new_chat_notification}.by(-1)
end

it "decreasing_post_notification_number" do
  expect(user).to receive(:checking_and_decreasing_notification).with(post_notification)
  user.decreasing_post_notification_number(post.id)
end

3 个答案:

答案 0 :(得分:1)

这样的事情:

describe '#task_name_company=' do
  let(:profile) { create(:profile, first_name: 'name', last_name: 'last', company: 'company') }
  let!(:user) { create(:user, profile: profile) }
  subject { create(:task) }

  it 'sets the executor' do
    subject.task_name_company = 'name last company'
    expect(subject.user).to eql user
  end
end

更新以回复let! vs let

describe '#task_name_company=' do
  let(:profile) { create(:profile, first_name: 'name', last_name: 'last', company: 'company') }
  let(:user) { create(:user, profile: profile) }
  subject { create(:task) }

  it 'sets the executor' do
    user # I'm explicitly calling user here
    subject.task_name_company = 'name last company'
    expect(subject.user).to eql user
  end
end

答案 1 :(得分:0)

这样的东西?

it "task_name_company setter" do
  expect(lambda {
    task.task_name_company = "blah"
  }).to  change{task.executor}.from(nil).to(user)
end

答案 2 :(得分:0)

我能够使它像这样...

css()

1)期望花费一个障碍

2)更改需要带有消息和/或expect { subject.total_batch_jobs = 1 } .to change(subject, :total_batch_jobs) .by(2)

的对象