2013-06-01 59 views
2

问候全部 - 我是rspec测试的新手,并且遵循Aaron Sumner的everydayrailsrspec pdf。我在我的控制器测试中遇到了redirect_to问题。我正在测试我的客户控制器中的创建操作。创建记录时,我将重定向到我的“列表”操作。试图测试这是给我适合。RSPEC Redirect_To语法

我的RSpec的控制器测试:

describe 'POST #create' do 
    context "with valid attributes" do 
    it "saves the new customer in the database" do 
     expect{ 
     post :create, customer: attributes_for(:customer) 
     } 
    end 

    it "redirects to list page" do 
     post :create, customer: attributes_for(:customer) 
     expect(response).to redirect_to(:action => list) 
    end 
    end 
end 

的, “这样可以节省...” 测试通过,但重定向一个没有。在pdf中,它显示了一个使用'customer_url'的例子。我从http://rspec.rubyforge.org/rspec-rails/1.1.12/classes/Spec/Rails/Matchers.html得到了我使用的语法(上面),但它不适用于我。

错误输出:

失败:

1) CustomersController while signed in POST #create with valid attributes redirects to list page 
Failure/Error: expect(response).to redirect_to(:action => list) 
NameError: 
    undefined local variable or method `customer' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_5::Nested_1:0x007fdcbfe88f20> 

我已经尝试添加控制器名称到测试中>> redirect_to的(:控制器=>客户:动作=>列表),但它也失败了。

帮助?谢谢。

回答

2

错误是说"customer is not defined"。我假设你正在使用FactoryGirl,并且你有一个customer工厂定义。如果这是正确的,那么你在customer哈希留出了Factory方法

it "redirects to list page" do 
    post :create, customer: Factory.attributes_for(:customer) 
    expect(response).to redirect_to(:action => list) 
end 

你也可以写像这样

it "redirects to list page" do 
    post :create, customer: Factory.attributes_for(:customer) 
    response.should redirect_to(:action => list) 
end 

此外,在第一次测试,我建议增加

it "saves the new customer in the database" do 
    expect{ 
    post :create, customer: Factory.attributes_for(:customer) 
    }.to change(Customer,:count).by(1) 
end 

这应该让你走上正轨

+0

感谢h elp,但那不行,对不起。我有一个客户工厂。我在我的spec_helper.rb中也有一行:#include Factory Factory语法来简化对工厂的调用 config.include FactoryGirl :: Syntax :: Methods这使我不必在我的create或build语句中使用Factory。如果我删除第二个'它'块,所有的测试都照原样传递。但是这个不会。另外,添加'工厂'会给我一个错误:'未初始化的常量工厂'我的spec中需要'spec_helper'。 –

+0

如何添加一个新行,以便可以将格式化的代码添加到这些注释中?如果我点击Return键,它会提交我的评论。 –

+0

使用反引用''示例'而不是''示例' – fontno