2012-09-25 29 views
1

我有以下如何比较Rspec中的分配?

it 'should assign a new profile to user' do 
    get :new 
    assigns(:user_profile).should ==(Profile.new) 
end 

但它不工作。我试过'eql?'和'平等'?分别。如何比较它以便了解@user_profile的内容是否为Profile.new?

我曾经做过一个解决方法,做一个指定变量的.class,检查它是否是Profile,但我想停止这些不好的做法。

谢谢。

回答

1

这里的问题是Object.new被设计调用两次创建两个不同对象,这是不相等的。

1.9.2p318 :001 > Object.new == Object.new 
=> false 

有一两件事你可以在这里做是

let(:profile){ Profile.new } 

it 'should assign a new profile to user' do 
    Profile.should_receive(:new).and_return profile 
    get :new 
    assigns(:user_profile).should eq profile 
end 

现在你没有真正创建一个新的配置文件时,控制器动作被调用,但你仍然考验这个Profile正在接收new,和您正在测试该方法的返回值是由控制器分配给@user_profile

+0

令人敬畏的兄弟,这正是我想要的! ;-) – thiagofm

+0

事实上,没有什么特别的理由可以使'profile'的值成为实际的'Profile'对象;它可以是任何东西。例如,'let(:profile){“一个新的配置文件”}'不会真的改变测试的功能。但没关系,因为在控制器测试中,你不想测试'Profile :: new'本身的功能。但是,如果在控制器操作的'@ user_profile'上调用其他方法,这可能会导致消息期望错误。 (然后另一个选项是'let(:profile){mock('Profile')。as_null_object}'。) – gregates