2

I'm having trouble with equality matchers in RSpec and Draper decorated objects.

Specs to show what's going on:

context 'how to use the right equality matcher' do
  let(:page) { build(:page) }
  let(:decorated_page) { page.decorate }

  it "should pass, but doesn't" do
    expect(decorated_page).to_not eq page
  end

  it 'proves the classes are different' do
    expect(decorated_page).to be_a PageDecorator
    expect(page).to be_a Page
    expect(decorated_page.class).to_not eq page.class
  end

  it 'has a work around' do
    expect(decorated_page).to be_decorated_with PageDecorator
    expect(page).to_not be_decorated_with PageDecorator
  end
end

I know RSpec has a few different equality checkers, and that eq is the "weakest" but I would have thought not having the same class would be a deal breaker.

As you can see, I have a work around for this case thanks to Draper's matchers. But I feel like I must be missing something for that test to fail.

Question:

What equality matcher should I use to get the should pass, but doesn't test to pass?

4

1 回答 1

1

我认为你遇到了两个误解。

  1. 您在询问是否测试页面是否经过装饰。你不应该对此进行测试。相反,您应该测试装饰的结果,即行为。例如,如果装饰器应该添加一个新方法“foo”,那么测试“foo”方法是否按您想要的方式工作。

  2. Draper 装饰器制作model.decorate == model. 这故意使装饰对测试代码“不可见”。例如,expect(decorated_page).to eq page会成功,因为 RSpec==用于比较,然后 Draper 正在拦截==。这就是为什么您的规范说“应该通过,但没有”的行为方式是这样的。

如果您确实想测试页面上发生的装饰,请尝试以下操作:

expect(decorated_page.object).to eq page

如果您确实想测试装饰页面与页面不同,请尝试以下操作:

expect(decorated_page.object_id).to_not eq page.object_id
于 2014-12-30T06:06:51.627 回答