我的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>
我已尝试将控制器名称添加到测试中,如&gt;&gt; redirect_to(:controller =&gt; customers,:action =&gt; list),但也失败了。
帮助?感谢。
答案 0 :(得分:2)
错误是"customer is not defined"
。我假设您正在使用FactoryGirl,并且您已定义customer
工厂。如果这是正确的,那么您在Factory
哈希
customer
方法
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
这可以让你走上正轨