测试在Rspec

时间:2015-11-27 11:13:45

标签: ruby-on-rails rspec activemodel

使用Rspec 3.4,我得到了一个Message类:

class Message
  include ActiveModel::Model 
end

以下控制器规范失败:

context "with invalid params" do
  it "assigns a newly created but unsaved message as @message" do
    post :create, { message: @invalid_attributes }
    expect(assigns(:message)).to be_a_new(Message)

失败消息是:

 Failure/Error: expect(assigns(:message)).to be_a_new(Message)
 NoMethodError:
   undefined method `new_record?' for #<Message:0x00000006dc8a88>

因此,当我调用new_record?时,看起来rspec调用了be_a_new(Message),并且由于我的Message类没有从ActiveRecord继承,所以我收到了这个错误。

如何测试assigns(:message)确实是我的Message类的新实例?

我尝试过以下方法:

# this works, but I don't like it
expect(assigns(:message).to_not be(nil) 

# these fail because the instances are not equal
expect(assigns(:message).to eq(Message.new)
expect(assigns(:message).to eql(Message.new)
expect(assigns(:message).to eqeul(Message.new)
expect(assigns(:message).to be(Message.new)

那么这是一种棘手的方式吗?

1 个答案:

答案 0 :(得分:1)

我认为你应该尝试以下:

expect( assigns(:message) ).to be_kind_of Message