我有幾個RSpec控制器測試。一些工作,有些不這樣做,我試圖弄清楚在地球上如何修復它們並使它們更加高效簡化和正確RSpec控制器測試
理想情況下,我想看看我是否可以將每個規範都轉換爲以下形式
subject { ... }
it { ... }
it { ... }
it { ... }
請注意,對於我的所有控制器規格,我已經爲實際控制器操作編寫了宏。這些宏都經過了測試,並且都可以正常工作,並且這些名稱使得它們顯得非常明顯。
我的「創建」測試:
formats ||= ["html", "js"]
formats.each do |format|
context "valid attributes" do
subject { do_post_create(:customer, valid_attributes, format) }
its(:response_code) { should eq(302)}
it { should redirect_to admin_customer_path(Customer.find_by_id(???))}
it { expect { subject }.to change(Customer, :count).by(1) }
end
context "invalid attributes" do
subject { do_post_create(:customer, invalid_attributes, format) }
its(:response_code) { should eq(200)}
it { should render_template :new }
it { expect { subject }.to_not change(Customer, :count).by(1) }
end
end
在這種規範,我一直在試圖找出一些方法來擺脫後聲明新創建的對象的ID。我嘗試過「Customer.last」,但這似乎不起作用。有什麼想法嗎?
我的「更新」規格:
formats ||= ["html", "js"]
formats.each do |format|
context "valid attributes" do
let(:object) { FactoryGirl.create(:customer) }
subject { do_put_update(class_to_symbol(model), object.id, attributes, format) }
its(:response_code) { should eq(302)}
it "does alter #{model}" do
do_put_update(class_to_symbol(model), object.id, attributes, format)
assigns(:customer).should eq(object)
flash[:notice].should =~ /Success/
object.reload
attributes.each do |key, value|
object.send(key.to_s).should eq(value)
end
end
end
context "invalid attributes" do
let(:object) { FactoryGirl.create("customer") }
let(:invalid_attributes) { {:username => "!"} }
subject { do_put_update(class_to_symbol(model), object.id, invalid_attributes, format) }
its(:response_code) { should eq(200)}
it "does not alter #{model}" do
do_put_update(class_to_symbol(model), object.id, invalid_attributes, format)
assigns(:customer).should eq(object)
flash[:notice].should =~ /Fail/
object.reload
attributes.each do |key, value|
object.send(key.to_s).should_not eq(value)
end
end
end
end
在更新測試,我想試圖表達的第二塊以更簡潔的方式,最好的方式,我可以使用相同的「主題「所有測試的聲明。那可能嗎?
呃,這些都是非常好的點 - 考慮我相信。順便說一句,爲什麼「Customer.last」會在我的規格中返回零? – Bryce