如何存根嵌套模型来测试视图?

时间:2013-10-18 15:12:20

标签: ruby-on-rails rspec

我有一个关系:Transaction belongs_to Post(has_many)

我有这个观点:

# /app/views/transactions/index.html.haml

%h3 Transactions
%table
  %tr 
    %th Item
    %th Description
    %th Money
  - @transactions.each do |transaction|
    %tr 
      %td= transaction.description
      %td= number_to_currency(transaction.money)
      %td= link_to transaction.post.title, transaction.post.link # (!)

如果我没有最后一行 - 我会像这样测试它:

before(:each) do
  assign(:transactions, [
    stub_model(Transaction,
      { description: "Posted", money: 9.99 }
    ),
    stub_model(Transaction,
      { description: "Posted", money: 9.99 }
    )
  ])
end

it "renders a list of transactions" do
  render
  assert_select "tr>th", :text => "Description"
  assert_select "tr>th", :text => "Money"
  assert_select "tr>td", :text => "Posted", :count => 2
  assert_select "tr>td", :text => number_to_currency(9.99).to_s, :count => 2
end

但我不知道如何测试视图的最后一行,它显示了它所属的帖子的信息。

我已经阅读了stub_chain,但无法弄清楚如何将其安装到存根模型中。
试图先将Post发布,然后为stubbed事务分配post_id - 也不起作用..

或者我应该在Capybara级别测试它?

1 个答案:

答案 0 :(得分:0)

找到了一条路。

刚做过:

before(:each) do
  assign(:transactions, [
    stub_model(Transaction,
      { description: "Posted", money: 9.99, post: mock_model(Post, FactoryGirl.attributes_for(:post)) }
    ),
    stub_model(Transaction,
      { description: "Posted", money: 9.99, post: mock_model(Post, FactoryGirl.attributes_for(:post)) }
    )
  ])
end