如何对返回不同模型对象的Rails模型进行单元测试?

时间:2016-02-08 21:30:53

标签: ruby-on-rails model-view-controller rspec

我定义了User模型和Profile

class User < ActiveRecord::Base
  has_one :profile

  def current_profile
    profile || create_profile
  end
end

因此current_profile方法返回现有的配置文件或创建一个新配置文件并返回它。如何为User编写单元测试以检查此方法是否正常工作?我应该以某种方式检查返回的对象是否是Profile对象?或者我应该检查配置文件的参数?我使用RSpec而不是minitest。

2 个答案:

答案 0 :(得分:1)

你应该测试两种情况:

要么返回现有的个人资料,要么创建一个新的个人资料并将其返回

使用上下文:

describe 'User' do
  describe 'current_profile' do
    context 'when there is an existing profile' do
      it 'should return the existing profile' do
        # call and test expectations
      end
    end

    context 'when there is no existing profile' do
      it 'should create and return the profile' do
        # call and test expectations
      end
    end
  end
end

还要记住在角色本身是new_record的情况下。在这种情况下,create_profile可能会失败,因为它会期望一个尚未存在的角色ID。

答案 1 :(得分:0)

也许是这样的:

describe User do
  describe 'current_profile' do
    context 'when there is an existing profile' do
      before(:each) do
        @profile = User.current_profile # creates a profile
      end
      it 'should return the existing profile' do
        expect(User.current_profile).to eq(@profile)
      end
      it 'should not change Profile.count' do # assuming you have a Profile Class
        expect{User.current_profile}.not_to change{Profile.count}
      end
      it 'should return a Profile object' do
        expect(@profile).to be_a(Profile)
      end
    end
    context 'when there is no existing profile' do
      it 'should change Profile.count by 1' do
        expect{User.current_profile}.to change{Profile.count}.by(1)
      end
      it 'should return a Profile object' do
        @profile = User.current_profile
        expect(@profile).to be_a(Profile)
      end
    end
  end
end