【问题标题】:rspec matcher for build in new action用于构建新操作的 rspec 匹配器
【发布时间】:2016-04-24 11:01:02
【问题描述】:

如果@product.industry_products.build 和其他匹配器在我的操作中定义,我可以如何/使用哪个匹配器进行测试?

products_controller

def new
  @product = Product.new
  authorize @product
  @product.industry_products.build
  @product.product_features.build
  @product.product_usecases.build
  @product.product_competitions.build
end    

products_controller_spec.rb

context "GET new" do
  let!(:profile) { create(:profile, user: @user) }
  before(:each) do
    get :new
  end

  it "assigns product" do
    expect(assigns(:product)).to be_a_new(Product)
  end

  it { is_expected.to respond_with 200 }
  it { is_expected.to render_template :new }
end

【问题讨论】:

    标签: ruby-on-rails testing rspec controller


    【解决方案1】:

    您可以使用模拟来检查您的代码中是否调用了某些方法:

    expect_any_instance_of(Product).to receive_message_chain(:industry_products, :build).and_call_original
    expect_any_instance_of(Product).to receive_message_chain(:product_features, :build).and_call_original
    

    这些应该在调用new 操作之前声明。

    但是,在我看来,在此示例中测试是否调用了某些方法并不是那么有用,因为您的控制器操作中没有条件逻辑。检查产品关联的存在可能是更可靠的测试。

    【讨论】:

    • Anthony,我在模型规范中有这些测试。所以你认为在这种情况下,没有必要测试控制器中是否设置了实例变量?
    • 在这种情况下,是的。如果您想测试它们是否被调用,只需使用expect(assigns(:project).industry_products.size).to eq(1)。或者,更好的是,确保 industry_products 字段实际显示在您的表单中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多