【问题标题】:How to compare assignments in Rspec?如何比较 Rspec 中的作业?
【发布时间】:2012-09-25 20:14:12
【问题描述】:

我有以下

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,但我想停止这些不良做法。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-3.2


    【解决方案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

    【讨论】:

    • 很棒的兄弟,这正是我想要的! ;-)
    • 事实上,没有特别的理由让profile 的值成为一个实际的Profile 对象;它可以是任何东西。例如,let(:profile){ "a new profile" } 不会真正改变测试的功能。但这没关系,因为在控制器测试中您不想测试Profile::new 本身的功能。但是,如果在控制器操作中对 @user_profile 调用其他方法,这可能会导致消息预期错误。 (那么另一个选项是let(:profile){ mock('Profile').as_null_object }。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多