嵌套资源不工作测试视图rspec

时间:2014-08-12 20:04:50

标签: ruby-on-rails rspec

我在规范视图rspec中遇到嵌套资源的问题,

我有这样的路线:

resources :customers do
  resources :charges
end

这是我使用rspec测试的视图:

require 'rails_helper'

RSpec.describe "charges/index", :type => :view do
  before(:each) do
    assign(:customers, [
      @customer1 = Customer.create!(
        :first_name => "tardjo",
        :last_name => "ea...ea...ea"
      ),
      @customer2 = Customer.create!(
        :first_name => "udin",
        :last_name => "penyok"
      )
    ])

    assign(:charges, [
      Charge.create!(
        :created => 1,
        :paid => false,
        :amount => 1.5,
        :currency => "Currency",
        :refunded => false,
        :disputed => false,
        :customer_id => @customer1.id
      ),
      Charge.create!(
        :created => 1,
        :paid => false,
        :amount => 1.5,
        :currency => "Currency",
        :refunded => false,
        :disputed => false,
        :customer_id => @customer2.id
      )
    ])
  end

  it "renders a list of charges" do
    render
    assert_select "tr>td", :text => 1.to_s, :count => 2
    assert_select "tr>td", :text => false.to_s, :count => 2
    assert_select "tr>td", :text => 1.5.to_s, :count => 2
    assert_select "tr>td", :text => "Currency".to_s, :count => 2
    assert_select "tr>td", :text => false.to_s, :count => 2
    assert_select "tr>td", :text => 2.to_s, :count => 2
    assert_select "tr>td", :text => false.to_s, :count => 2
  end
end

但是我得到这样的错误:

失败/错误:渲染

::的ActionView模板::错误:    没有路由匹配{:customer_id => nil,:id => 1}缺少必需的密钥:[:customer_id]

卡在这里

1 个答案:

答案 0 :(得分:0)

这很可能是一个范围问题

尝试:

# these variables might need to be defined outside of the `:customers` array
@customer1 = Customer.create!(
    :first_name => "tardjo",
    :last_name => "ea...ea...ea"
)
@customer2 = Customer.create!(
    :first_name => "udin",
    :last_name => "penyok"
)
assign(:customers, [  @customer1, @customer2  ])